How do I get the member to which my custom attribute was applied?

Attributes provide metadata and don’t know anything about the thing (class, member, etc.) they are decorating. On the other hand, the thing being decorated can ask for the attributes it is decorated with.

If you must know the type of the thing being decorated you will need to explicitly pass it to your attribute in its constructor.

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, 
    AllowMultiple = true)] 
public class MyCustomAttribute : Attribute
{
   Type type;

   public MyCustomAttribute(Type type)
   {
      this.type = type;
   }
}

Leave a Comment