6

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?

Lali
  • 2,816
  • 4
  • 30
  • 47
  • See http://stackoverflow.com/questions/6042937/how-can-i-add-this-method-as-an-extension-method-to-properties-of-my-class – Black0ut Sep 03 '15 at 13:08
  • This is not what I am asking for.... – Lali Sep 03 '15 at 13:15
  • it's seems like exactly what you are asking for – Black0ut Sep 03 '15 at 13:21
  • I need this `this.PublishDateTime.Name()`, Would you tell me how to create extension method to do so? I already have done what is given in the link. – Lali Sep 03 '15 at 13:23
  • Possible duplicate of [Linq expressions and extension methods to get property name](http://stackoverflow.com/questions/5252176/linq-expressions-and-extension-methods-to-get-property-name) – Michael Freidgeim Apr 23 '16 at 13:27

3 Answers3

13

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);
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30
11

With C# 6.0, you can use:

nameof(PublishDateTime)
janhartmann
  • 14,713
  • 15
  • 82
  • 138
2

You can't do this.PublishDateTime.Name(), as the only thing that will be passed into the extension method is the value or reference on which you call the extension method.

Whether it's a property, field, local variable or method result doesn't matter, it won't have a name that you can access inside the extension method.

The expression will be "verbose", see How can I add this method as an extension method to properties of my class? (thanks @Black0ut) to put it in a static helper class.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Why I can't do this? When I am calling `this.PublishDateTime.Name()`, it means I am passing object to extension method. Now extension method should create expression by itself. I want to modify the extension method. There must be some soft solution for this... – Lali Sep 03 '15 at 13:15
  • You can do it, but it won't give you the member name. The extension method doesn't "know" it's being called on a member, and it doesn't have to be (`string foo = ""; var fooName = foo.Name()`). All that will be passed to the extension method is the value of, or a reference to the object you call it on. – CodeCaster Sep 03 '15 at 13:20