Dmitry
Dmitry

Reputation: 1320

How can attribute's code know what type it's applied to?

public class SomeAttr: Attribute
{
    void Method()
    {
        //here I want to know the type this instance of attribute is applied to
    }
}

Upvotes: 3

Views: 126

Answers (2)

Polyfun
Polyfun

Reputation: 9639

Pass the type (using typeof) into the Attribute constructor, e.g,.

class SomeAttr : Attribute
{
    private Type _type;

    public SomeAttr(Type type)
    {
        _type = type;
    }

    private void Method()
    {
        string s = _type.ToString(); // Example usage of type.
    }
}

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062745

In regular .NET, it doesn't and can't (unless you tell it manually); sorry. You'll need to include some typeof(Foo) in the attribute constructor / properties. If you are talking AOP (PostSharp etc), then all bets are off.

If you mean some of the attributes used by TypeDescriptor ([DisplayName], [TypeConverter], etc), then there may be other options - but rather specific and non-trivial to implement.

Upvotes: 2

Related Questions