Daniel Powell
Daniel Powell

Reputation: 8303

get an attributes class

Is it possible in C# in an attribute constructor to get the class that has the attribute assigned to it without having to pass that class name in.

    [MyAttr]
    public class A{}

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    [Serializable]
    public class MyAttrAttribute: Attribute
    {
        public MyAttrAttribute()
        {
           //get info here about the class A etc
        }    
    }

Upvotes: 3

Views: 252

Answers (3)

phoog
phoog

Reputation: 43056

No. But why would you want to do this? What are you trying to achieve?

When you retrieve an attribute at run time, you do so from the type object representing the class. So even though the information is not stored in the attribute object, it is readily available.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064114

Attribute instances are completely independent of the types/fields/properties that they decorate; there is absolutely no way of accessing the context from an attribute. However, attributes also aren't created until you explicitly query them with reflection.

If you want to invoke some logic, then it must be done explicitly through code - so you might consider adding a method on your attribute that accepts the context object:

public void Invoke(object instance) {...}

for example, then use GetCustomAttribute to obtain it, cast it, and call .Invoke()

Upvotes: 3

misosim
misosim

Reputation: 11

This would have been a convenient feature, nice question. But fundamentally attributes are meant only as meta data to inspectors not to be inspectors - they are constant data.

Upvotes: 0

Related Questions