I am looking for the most condensed and clean way to get an attribute of a member without an instance of the object. The member is not static either.
In my case I need the DisplayName of a DisplayNameAttribute of a property:
public class MyClass
{
[DisplayName("MyName")]
public int someVar {get;set;}
}
The most condensed I can currently come up with is this:
public static string MyHelperMethod<T>(System.Linq.Expressions.Expression<Func<T, object>> expr)
{
return (expr.Body as System.Linq.Expressions.MemberExpression)?.Member?.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? string.Empty;
}
//somewhere in code
string displayName = MyHelperMethod<MyClass>(x => x.someVar);
What I would like is this:
public static string MyHelperMethod???
{
???
}
//somewhere in code
string displayName = MyHelperMethod(MyClass.someVar);
Is this possible? If the only answer contains ugly-hacky code I will not use it but it still might be interesting to know.