Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<Func<TModel,TValue>> how can i get TValue's name?

//ModelFor(person =>person.Name);
public void ModelFor<TModel, TValue>(
    Expression<Func<TModel, TValue>> expression)
{
    //Result should be "Name"
    string nameOfTValue = ????;     
}
like image 709
Freshblood Avatar asked Jan 05 '11 16:01

Freshblood


1 Answers

EDIT: After your edit, I think you are want the name of the member involved in the expression, assuming of course that the expression is a member-expression in the first place.

((MemberExpression)expression.Body).Member.Name

To be more robust, you can do:

var memberEx = expression.Body as MemberExpression;

if (memberEx == null)
     throw new ArgumentException("Body not a member-expression.");

string name = memberEx.Member.Name;

(Not relevant anymore):

To get a System.Type that represents the type of the TValue type-argument, you can use the typeof operator.

You probably want:

typeof(TValue).Name

But also consider the FullName and AssemblyQualifiedName properties if appropriate.

This really has nothing to do with expression-trees; you can use this technique to get the type of a type-argument for any generic method.

like image 157
Ani Avatar answered Sep 28 '22 17:09

Ani