Given a simple piece of code which can return the name of a property in VB.NET:
Function NameForProperty(Of T)(ByVal field As Expression(Of Action(Of T))) As String
Dim expression = DirectCast(field.Body, MemberExpression)
Return expression.Member.Name
End Function
Which works like this:
NameForProperty(Of String)(Function (s) s.Length) ' ==> returns "Length"
And what I thought would have been the equivalent in C#:
string NameForProperty<T>(Expression<Action<T>> field)
{
var expression = (MemberExpression)field.Body;
return expression.Member.Name;
}
When I try to call the C# version:
NameForProperty<string>(s=>s.Length);
It returns a compiler error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
My question is: what is the difference between the two pieces of code?
EDIT
Ivan has provided an answer as to why the code does not work in C#. I am still curious as to why it does work in VB.NET.
EDIT#2
To be clear, I'm not looking for code which works -- simply why the code would work in VB.NET and not C#.