jondavidjohn
jondavidjohn

Reputation: 62412

evaluate a string as a property in C#

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};

Upvotes: 7

Views: 2103

Answers (3)

msarchet
msarchet

Reputation: 15242

You need to use reflection to do this.

Something like this should take care of you

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

Upvotes: 3

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391624

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.

Upvotes: 3

Bala R
Bala R

Reputation: 109017

Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)

Upvotes: 8

Related Questions