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.