Evaluate string as property in C #

I have a property stored in a string ... say Object Foohas a property Bar, so to get the value of the property BarI would call ..

Console.Write(foo.Bar);

Now tell me what I have "Bar", stored in a string variable ...

string property = "Bar"

Foo foo = new Foo();

how to get the value foo.Barwith property?

How do I use this in PHP

$property = "Bar";

$foo = new Foo();

echo $foo->{$property};
+5
source share
3 answers
Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)
+6
source

You would use reflection:

PropertyInfo propertyInfo = foo.GetType().GetProperty(property);
object value = propertyInfo.GetValue(foo, null);

null in the call is for indexed properties, which is not what you have.

+1
source

.

-

foo.GetType().GetProperty(property).GetValue(foo, null);
+1

All Articles