7

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};
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158

3 Answers3

8
Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)
Bala R
  • 107,317
  • 23
  • 199
  • 210
3

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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
3

You need to use reflection to do this.

Something like this should take care of you

foo.GetType().GetProperty(property).GetValue(foo, null);
msarchet
  • 15,104
  • 2
  • 43
  • 66