At what time during runtime does an attribute constructor get run?

Trying to find some verbose reference on the intricacies of Attributes. Any help would be appreciated.

At this point, I'd specifically like to know what time during runtime does an attribute constructor get ran?

Thanks.

Upvotes: 2

Views: 442

Answers (4)

Jone Polvora
Jone Polvora

Reputation: 2338

Attribute are decorations that stores metadata or informations about a type. .Net framework utilizes heavily this kind of information to do additional processing when creating instances.

The attribute is constructed only when asked by some other class, with Type.GetCustomAttributes() for example. So, even you can create your own attributes and then asks for your custom attributes.

public class MyOwnAttribute: Attribute {}

/* at some point in another class */

void CheckIfClassIsDecoratedWithMyOwnAttribute()
{
    var instance = new MyClass();
    if (instance.GetType().GetCustomAttributes(typeof(MyOwnAttribute)))
    {
       //do whatever you want
    }
}

Upvotes: 0

albertein
albertein

Reputation: 27150

The only thing that you can be sure is that it'll be called before is needed. It's not defined the exact time the constructor will be called.

Anyway, the behaviour is unespecified, so you shouldn't rely on whenever the constructur gets called by the current implementation.

Upvotes: 2

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

Reading the norm (17.3.2 in the C# 2.0 version) it's unspecified. Only the way to convert from the metatada to an instance is.

So you may need to test on different implementations, because if it isn't specified it's bound to be interpreted differently.

Upvotes: 3

Rex M
Rex M

Reputation: 144202

The constructor is invoked when you call GetCustomAttributes() on the type or MemberInfo.

Upvotes: 3

Related Questions