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?
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);
With C# 6.0, you can use:
nameof(PublishDateTime)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With