Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method to get property name

I have an extension method to get property name as

public static string Name<T>(this Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

I am calling it as

string Name = ((Expression<Func<DateTime>>)(() => this.PublishDateTime)).Name();

This is working fine and returns me PublishDateTime as string.

However I have an issue with the calling statement, it is looking too complex and I want some thing like this.

this.PublishDateTime.Name()

Can some one modify my extension method?

like image 941
Lali Avatar asked Sep 03 '15 13:09

Lali


2 Answers

Try this:

public static string Name<T,TProp>(this T o, Expression<Func<T,TProp>> propertySelector)
{
    MemberExpression body = (MemberExpression)propertySelector.Body;
    return body.Member.Name;
}

The usage is:

this.Name(x=>x.PublishDateTime);
like image 100
Taher Rahgooy Avatar answered Oct 23 '22 22:10

Taher Rahgooy


With C# 6.0, you can use:

nameof(PublishDateTime)
like image 22
janhartmann Avatar answered Oct 23 '22 21:10

janhartmann