[Dev Tip] Get name of property, get information of method

1) name of property

Using Expression:

// requires object instance, but you can skip specifying T
static string GetPropertyName<T>(Expression<Func<T>> exp)
return (((MemberExpression)(exp.Body)).Member).Name;

// requires explicit specification of both object type and property type
static string GetPropertyName<TObject, TResult>(Expression<Func<TObject, TResult>> exp)
// extract property name
return (((MemberExpression)(exp.Body)).Member).Name;

// requires explicit specification of object type
static string GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)
return (((MemberExpression)(exp.Body)).Member).Name;


var x = new ObjectType();
// note that in this case we don't need to specify types of x and Property1
var propName1 = GetPropertyName(() => x.Property1);
// assumes Property2 is an int property
var propName2 = GetPropertyName<ObjectType, int>(y => y.Property2);
// requires only object type
var propName3 = GetPropertyName<ObjectType>(y => y.Property3);

2) information of method

2.1) input

public interface IMyInteface
void DoSomething(string param1, string param2);

method to get

MemberInfo GetMethodInfo<T>(Expression<Func<T, Delegate>> expression)
 var unaryExpression = (UnaryExpression) expression.Body;
 var methodCallExpression = (MethodCallExpression) unaryExpression.Operand;
 var methodInfoExpression = (ConstantExpression) methodCallExpression.Arguments.Last();
 var methodInfo = (MemberInfo) methodInfoExpression.Value;
 return methodInfo;

And use

var methodInfo = GetMethodInfo<IMyInteface>(x => new Action<string, string>(x.DoSomething))

Note: It works for current interface, but probably some generalization will be required to make this working with any method.