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?
You can't create "static" extension methods.
Extension methods are "instance" methods.
You could just provide a helper class:-
Extension methods are type-specific (even when they are generic), you can't have an extension method for a property without having the same extension method available to all items that are of that type.
If you have an extension method for a specific type, it won't matter if it's a Property or a local variable or a class member, the extension method will still be availabe.
I'm clearly not an expert like Jon but this seems to me that what you want and is fairly simple (that's why I doubt, since Jon is clearly a reference person ! ;-)) :
It compiles and meet the requirements, from what I can see. You probably should have found it yourself, since you spoke about an extension method from start...
No, it's not possible to do that. It's not clear whether
MyClass
is the name of a class (andProperty1
is a static property) or whether it's an instance property andMyClass.Property1
simply 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
string
can be inferred:That would be something like: