views:

49

answers:

3

I've found that attributes in C# seem to be lazily instantiated.

[A(123)]
class A : Attribute
{
    public A(int b)
    {
        GetType().GetCustomAttributes(true);
    }
}

In this example, creating a new A instance causes a StackOverflowException, but if I remove the call to GetCustomAttributes(), then execution carries on normally.

Why is this? It makes more sense to me that attributes are properly initialized when the class they decorate is.

+1  A: 

Why the runtime would need to instantiate all attributes on class before you requested them? It is like asking why runtime does not create an instance of my class in advance, just in case I want to use it later.

Attributes are meta data on class, they do not affect the class work in any way. Only the code the requests the attribute care about it, no one else is not. So the current behavior does make sense.

Alex Reitbort
+1  A: 

Since attribute functionality is only ever executed by code that is actively looking for the attribute in question, it's wasteful for the runtime to instantiate attributes until they are first used - indeed, during the lifetime of a program, attributes may never be inspected.

Bradley Smith
+1  A: 

Attributes are "information" associated to a type, and not to an instance.
There is no reason why they should be instantiated when you create an object of the type they are attached to, instead you can see them when you're inspecting the type itself.

Paolo Tedesco