3

In PHP I can use a variable variable to access a class property dynamically like so:

class foo 
{
    public $bar = 'test';
}

$a = 'bar'; 
$obj = new foo;

echo $obj->$a; // output 'test'

How can I do something like this in C#?

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
NemanjaLazic
  • 604
  • 4
  • 12
  • Things like [PHP's variable variable](http://php.net/manual/en/language.variables.variable.php) are not possible in C# out of the box. What do you actually need to accomplish? – SWeko Sep 03 '13 at 13:34
  • 4
    It's possible using reflection, but in *most* cases it's not necessary and is an indication that a different data structure should be used. Can you give context as to why you need to do this? – David Sep 03 '13 at 13:34
  • 1
    In C# you would typically need to use reflection to use the properties dynamically. This isn't usually a good idea since you lose compile time goodness. – StuartLC Sep 03 '13 at 13:37
  • 1
    You can acomplish something simillar with the "dynamic" type, but if you are serious about working with C#, I would suggest you change your mindset to use the language in the way it was designed to be used, instead of trying to write code like you would do in php but with C# syntax. The code you wrote is thought for a dynamically typed language :-) – Philippe Sep 03 '13 at 13:40
  • 2
    This shouldn't be closed it's a perfectly valid question. – Rudi Visser Sep 03 '13 at 13:49

2 Answers2

2

Assuming:

public class Foo
{
    public String bar { get; set; }
}

// instance that you want the value from
var instance = new Foo { bar = "baz" };

// name of property you care about
String propName = "bar";

You can use:

// Use Reflection (ProperyInfo) to reference the property
PropertyInfo pi = instance.GetType()
    .GetProperty(propName);

// then use GetValue to access it (and cast as necessary)
String valueOfBar = (String)pi.GetValue(instance);

End result:

Console.WriteLine(valueOfBar); // "baz"

to make things easier:

public static class PropertyExtensions
{
    public static Object ValueOfProperty(this Object instance, String propertyName)
    {
        PropertyInfo propertyInfo = instance.GetType().GetProperty(propertyName);
        if (propertyInfo != null)
        {
            return propertyInfo.GetValue(instance);
        }
        return null;
    }

    public static Object ValueOfProperty<T>(this Object instance, String propertyName)
    {
        return (T)instance.ValueOfProperty(propertyName);
    }
}

And given the same assumptions as above:

// cast it yourself:
Console.WriteLine((String)instance.ValueOfProperty(propName)); // "baz"

// use generic argument to cast it for you:
Console.WriteLine(instance.ValueOfProperty<String>(propName)); // "baz"
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

You wouldn't do something like that, variable variables are not supported in C#. You could use reflection to get a property value, but that's a whole other beast since you will be losing strong-typing etc. Quite simply it comes down to why do you want to do this? You shouldn't need to, in most cases as there are generally better alternatives than runtime resolution of values.

What you can do instead is use a string based dictionary (ie. Dictionary<string, string>) to index your values by a key.

You can then do something like this:

class Foo
{
    public Dictionary<string, string> values = new Dictionary<string, string>();

    public Foo()
    {
        values["foo"] = "test";
    }
}

var test = "foo";
var foo = new Foo();
Console.WriteLine(foo.values[test]);
Community
  • 1
  • 1
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97