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

Usage

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.

 

 

 

 

 

 

 

 

Advertisements

One thought on “[Dev Tip] Get name of property, get information of method

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 )

Google+ photo

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

Connecting to %s