Pass Property as Expression

I recently needed to pass a property of a class as an expression to a method and read value from it. I found the code that I finally ended up interesting and thought it might be useful to share it here.

void Main()
{
var instance = new Test();
instance.FName= "jia";
PrintMethod(x=>x.FName,instance);
}
public void PrintMethod(Expression<Func> action,dynamic instance)
{
var memberExpr = action.Body as MemberExpression;
var propInfo = memberExpr.Member as PropertyInfo;
var value = propInfo.GetValue(instance);
Console.WriteLine(value);
}

class Test
{
public string FName{get;set;}
public string LName{get;set;}
}

It might look I could have passed the value directly instead of as an expression, but the real life scenario was much complex than one demonstrated in the example.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s