.NET Attributes: Why does GetCustomAttributes() make a new attribute instance every time?

Attributes aren't stored in memory as objects, they're only stored as metadata in the assembly. When you query for it, it will be constructed and returned, and usually attributes are throwaway objects so for the runtime to keep them around just in case you'd need them again would probably waste a lot of memory.

In short, you need to find another way to store your shared information.

Here's the documentation on attributes.


Object-creation is cheap.

If you had an attribute like

public class MyAttribute : Attribute {
    public virtual string MyText { get; set; }
}

and applied it to a class like

[MyAttribute(MyText="some text")]
public class MyClass {
}

and you retrieved one like

var attr =
    typeof(MyClass).GetCustomAttributes(typeof(MyAttribute), false)
    .Cast<MyAttribute>().Single();

and you set some properties on it like

attr.MyText = "not the text we started with";

what should happen, and what would happen, the next time you called

Console.WriteLine(
    typeof(MyClass).GetCustomAttributes(typeof(MyAttribute), false)
    .Cast<MyAttribute>().Single().Name
);

?


It's because the attributes are saved in metadata. Attributes should be used for informations such as "user-friendly name of property", etc...