user47322
user47322

Reputation:

Why are attributes lazily instantiated?

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.

Upvotes: 2

Views: 788

Answers (3)

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

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.

Upvotes: 1

Bradley Smith
Bradley Smith

Reputation: 13601

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.

Upvotes: 2

Alex Reitbort
Alex Reitbort

Reputation: 13696

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.

Upvotes: 3

Related Questions