I have a property stored in a string... say Object Foo
has a property Bar
, so to get the value of the Bar
property I would call..
Console.Write(foo.Bar);
Now say that I have "Bar"
stored in a string variable...
string property = "Bar"
Foo foo = new Foo();
how would I get the value of foo.Bar
using property
?
How I'm use to doing it in PHP
$property = "Bar";
$foo = new Foo();
echo $foo->{$property};
Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)
You would use reflection:
PropertyInfo propertyInfo = foo.GetType().GetProperty(property);
object value = propertyInfo.GetValue(foo, null);
The null
in the call there is for indexed properties, which is not what you have.
You need to use reflection to do this.
Something like this should take care of you
foo.GetType().GetProperty(property).GetValue(foo, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With