Question

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?

  • If it's over a class
  • If it's over a property
  • If it's over a method

Thanks.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top