Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluate a string as a property in C#

Tags:

c#

properties

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};
like image 948
jondavidjohn Avatar asked Jun 15 '11 20:06

jondavidjohn


3 Answers

Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)
like image 170
Bala R Avatar answered Nov 04 '22 08:11

Bala R


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.

like image 37
Lasse V. Karlsen Avatar answered Nov 04 '22 07:11

Lasse V. Karlsen


You need to use reflection to do this.

Something like this should take care of you

foo.GetType().GetProperty(property).GetValue(foo, null);
like image 2
msarchet Avatar answered Nov 04 '22 08:11

msarchet