Using Expression<TDelegate> In C#

With System.Reflection

Today, When I chatted with my friend Miko, She asked me how to access object’s member via lambda expression in C#

You need import the namespace ‘System.Linq.Expression’ and ‘System.Reflection’ at firs like this :

using System.Linq.Expression; 
using System.Reflection;

You will be seeing the ‘ Expression<>’ shown on your Intellisense after imported the namespaces.

Now I need some code to access the object’s member.

public MemberInfo GetMemberInfo<T>(Expression<Func<T,object>> selector)
=>(selector.Body as MemberExpression)?throw new NotSupportedException(“Not supported this lambda expression”);

So when I using this method

class Test 
{
public string TestProperty { get; set; }
}
...
var memberName = GetMemberInfo<Test>(test => test.Name).Name;

Then I will be getting the member’s name(‘TestProperty’) from the Test class via GetMemberInfo<T> function.

Here is the sample code for store the member’s value from new T instance.

... 
public T SetValue<T>(Expression<Func<T,object>> selector, object value)where T:new()
{
var member =(selector.Body as MemberExpression)?throw new NotSupportedException(“Not supported this lambda expression”);
var target = new T();
switch(member)
{
case PropertyInfo p:
p.SetValue(target,value);
break;
case FieldInfo f:
f.SetValue(target,value);
break;
}
return target;
}

This is my Github Repository,I was implemented some code to mapped Excel’s Sheet to object’s fields.