Is there a better way to get the Property name when passed in via a lambda expression? Here is what i currently have.
eg.
GetSortingInfo
With C# 7 pattern matching:
public static string GetMemberName(this Expression expression)
{
switch (expression.Body)
{
case MemberExpression m:
return m.Member.Name;
case UnaryExpression u when u.Operand is MemberExpression m:
return m.Member.Name;
default:
throw new NotImplementedException(expression.GetType().ToString());
}
}
Example:
public static RouteValueDictionary GetInfo(this HtmlHelper html,
Expression> action) where T : class
{
var name = action.GetMemberName();
return GetInfo(html, name);
}
[Update] C# 8 pattern matching:
public static string GetMemberName(this Expression expression) =>
expression.Body switch
{
MemberExpression m =>
m.Member.Name,
UnaryExpression u when u.Operand is MemberExpression m =>
m.Member.Name,
_ =>
throw new NotImplementedException(expression.GetType().ToString())
};