I have a method and I want to add this method as an extension method to properties of my class.
This method give an expression as input parameter. The method is like below :
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
I want to use this method like below example :
string propertyName = MyClass.Property1.GetPropertyName();
Is it possible? if yes, what is the solution?
No, it’s not possible to do that. It’s not clear whether
MyClassis the name of a class (andProperty1is a static property) or whether it’s an instance property andMyClass.Property1simply isn’t a valid member access. If it’s the latter, you probably want to change your method to something like:and call it as:
Or you could use a generic class with a generic method, so that
stringcan be inferred:That would be something like: