I have a method which i want to convert to Extension Method
public static string GetMemberName<T>(Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
and calling it like
string str = myclass.GetMemberName(() => new Foo().Bar);
so it evaluates to str = "Bar"; // It gives the Member name and not its value
Now when i try to convert this to extension method by this
public static string GetMemberName<T>(this Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
and call it like
string str = (() => new Foo().Bar).GetMemberName();
Error says Operator '.' cannot be applied to operand of type 'lambda expression'
Where am I wrong?
There are really two things here, first, passing
() => new Foo().Barinto the method that acceptsExpression<Func<T>>treats the specified expression tree as aExpression<Func<T>>, but() => new Foo().Baris not anExpression<Func<T>>on its own.Second, in order to get your extension method to accept any lambda (such as you’re supplying), you’d have to use the type that corresponds to any expression tree. But, as you may have already guessed based on the message
... to operand of type 'lambda expression'where you’d usually see the name of the type inside the quotes, that lambda expressions are treated specially by the language, making what you’re trying to do, without casting first, impossible.The way to invoke your extension method in extension method form would be (in the case that
Baris of typestring)which doesn’t seem like it would be all that desirable.