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#?
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#?
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"
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]);