I created a method in C# to get methodname
public string GetCorrectPropertyName<T>(Expression<Func<T, string>> expression)
{
return ((MemberExpression)expression.Body).Member.Name; // Failure Point
}
and calling it as
string lcl_name = false;
public string Name
{
get { return lcl_name ; }
set
{
lcl_name = value;
OnPropertyChanged(GetCorrectPropertyName<ThisClassName>(x => x.Name));
}
}
This works fine if property is string and for all other types gives this exception:
Unable to cast object of type 'System.Linq.Expressions.UnaryExpression' to type 'System.Linq.Expressions.MemberExpression'.
- I changed string to object in method signature, but then it fails again.
- I changed calling from
x => x.PropertyName
tox => Convert.ToString(x.PropertyName)
and it still fails
Where am I wrong?
After asking this question(yes I am OP) i received comments on question from Jon
and I came up with this
You need a separate line to extract the Member where the input expression is a Unary Expression.
Just converted this from VB.Net, so might be slightly off - let me know if I need to make any minor tweaks:
The VB version is:
Note that the input expression does not return string necessarily - that constrains you to only reading properties that return strings.
This is apparently related to boxing/unboxing. Lambda expressions returning value types that require boxing will be represented as UnaryExpressions whereas those that return reference types will be represented as MemberExpressions.