2

Given a custom attribute, I want to get the name of its target:

public class Example
{
    [Woop] ////// basically I want to get "Size" datamember name from the attribute
    public float Size;
}

public class Tester
{
    public static void Main()
    {
        Type type = typeof(Example);
        object[] attributes = type.GetCustomAttributes(typeof(WoopAttribute), false);

        foreach (var attribute in attributes)
        {
            // I have the attribute, but what is the name of it's target? (Example.Size)
            attribute.GetTargetName(); //??
        }
    }
}

Hope it's clear!

Waldo Bronchart
  • 10,152
  • 4
  • 23
  • 29
  • 1
    Better solutions exist in [Can C# Attributes access the Target Class?](https://stackoverflow.com/questions/2308020/can-c-sharp-attributes-access-the-target-class). Actually, [CallerMemberNameAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?redirectedfrom=MSDN&view=netframework-4.8) is the current state-of-the-art for this. – Rodrigo Rodrigues Jul 07 '19 at 02:50

1 Answers1

7

do it the other way around:

iterate

 MemberInfo[] members = type.GetMembers();

and request

 Object[] myAttributes = members[i].GetCustomAttributes(true);

or

 foreach(MemberInfo member in type.GetMembers()) {
     Object[] myAttributes = member.GetCustomAttributes(typeof(WoopAttribute),true);
     if(myAttributes.Length > 0)
     {
        MemberInfo woopmember = member; //<--- gotcha
     }
 }

but much nicer with Linq:

var members = from member in type.GetMembers()
    from attribute in member.GetCustomAttributes(typeof(WoopAttribute),true)
    select member;
Caspar Kleijne
  • 21,552
  • 13
  • 72
  • 102
  • cheers, I was hoping there was a direct access. But this works well enough. I'll worry about it once (or IF) I get performance issues I guess – Waldo Bronchart Jan 29 '11 at 00:21