0

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.

Tom
  • 503
  • 2
  • 13
  • Have you tried extension methods? – PmanAce Mar 29 '18 at 15:44
  • Consider: if `someVar` was `static`, there'd be literally no way to distinguish between passing its value and passing it for metadata purposes, so your proposed syntax is too simple for its own good. – Jeroen Mostert Mar 29 '18 at 15:45
  • private static string GetCode(object val) { var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : string.Empty; } – PmanAce Mar 29 '18 at 15:47
  • @PmanAce extension methods will not work as this is used for many types. – Tom Mar 29 '18 at 16:10
  • @JeroenMostert Ye I understand but thought there would be some way unkown to me. So I guess the answer is no, it can't be done. – Tom Mar 29 '18 at 16:11
  • My extension method accepts object, thus ALL my enums use GetCode(), go see my answer in the existing question. – PmanAce Mar 29 '18 at 16:29
  • https://stackoverflow.com/questions/3289198/custom-attribute-on-property-getting-type-and-value-of-attributed-property – PmanAce Mar 29 '18 at 16:35
  • I will think about it, thanks! – Tom Mar 29 '18 at 16:41

0 Answers0