88

When is it run? Does it run for each object to which I apply it, or just once? Can it do anything, or its actions are restricted?

0

4 Answers 4

87

When is the constructor run? Try it out with a sample:

class Program { static void Main(string[] args) { Console.WriteLine("Creating MyClass instance"); MyClass mc = new MyClass(); Console.WriteLine("Setting value in MyClass instance"); mc.Value = 1; Console.WriteLine("Getting attributes for MyClass type"); object[] attributes = typeof(MyClass).GetCustomAttributes(true); } } [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { public MyAttribute() { Console.WriteLine("Running constructor"); } } [MyAttribute] class MyClass { public int Value { get; set; } } 

And what is the output?

Creating MyClass instance Setting value in MyClass instance Getting attributes for MyClass type Running constructor 

So, the attribute constructor is run when we start to examine the attribute. Note that the attribute is fetched from the type, not the instance of the type.

Sign up to request clarification or add additional context in comments.

8 Comments

Note that the constructor is run multiple times if you call GetCustomAttributes multiple times.
Yes, that is good to point out; there is no caching going on for the attributes (as opposed to the Type objects that, as far as I recall, are cached while the application is running).
Anyone know why the attribute objects aren't cached?
@Matt: I don't know, but my guess would be that Type object are used frequently enough to make it interesting to make the investment of caching them, while that may not be the case with Attributes. But I am just speculating.
You may also add code in the constructor of your attribute for instance to change values according to the context. if the attribute is cached you can't do that.
|
23

The constructor is run every time the GetCustomAttributes is invoked, or whenever some other code invokes the constructor directly (not that there's a good reason to do so, but it's not impossible either).

Note that at least in .NET 4.0, the attribute instances are not cached; a fresh instance is constructed every time GetCustomAttributes is called:

[Test] class Program { public static int SomeValue; [Test] public static void Main(string[] args) { var method = typeof(Program).GetMethod("Main"); var type = typeof(Program); SomeValue = 1; Console.WriteLine(method.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "1" SomeValue = 2; Console.WriteLine(method.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "2" SomeValue = 3; Console.WriteLine(type.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "3" SomeValue = 4; Console.WriteLine(type.GetCustomAttributes(false) .OfType<TestAttribute>().First().SomeValue); // prints "4" Console.ReadLine(); } } [AttributeUsage(AttributeTargets.All)] class TestAttribute : Attribute { public int SomeValue { get; private set; } public TestAttribute() { SomeValue = Program.SomeValue; } } 

It is not the best idea to have attributes behave like this, of course. At the very least, note that GetCustomAttributes is not documented to behave like this; in fact, what happens in the above program is not specified in the documentation.

2 Comments

That's the way it was meant to behave (the verb "get" implies action). GetCustomAttributes MUST return fresh copies every time. That's the only way to guarantee the code executed in the constructor of the attribute is examining a relevant context. With dynamic assemblies, interception, and everything else, there's no telling what could have changed since that last call. It may even return a different set of attributes based on a real time setting.
@PaulEaster I do agree that this behaviour is clearly by-design, enabling some interesting attribute constructors. But when I was less experienced with .NET, it seemed intuitive that since attributes are baked into the assembly metadata, they cannot possibly change during program runtime (but it turned out they can). So such constructors can certainly give someone a nasty surprise.
8

Set a debugger break-point inside an attribute constructor and write some reflection code that reads those attributes. You'll notice that the attribute objects won't be created until they are returned from the relfection API. Attributes are per class. They are part of the meta data.

Have a look at this:

Program.cs

using System; using System.Linq; [My(15)] class Program { static void Main(string[] args) { Console.WriteLine("Program started"); var ats = from a in typeof(Program).GetCustomAttributes(typeof(MyAttribute), true) let a2 = a as MyAttribute where a2 != null select a2; foreach(var a in ats) Console.WriteLine(a.Value); Console.WriteLine("Program ended"); Console.ReadLine(); } } 

MyAttribute.cs

using System; [AttributeUsage(validOn : AttributeTargets.Class)] public class MyAttribute : Attribute { public MyAttribute(int x) { Console.WriteLine("MyAttribute created with {0}.", x); Value = x; } public int Value { get; private set; } } 

Result

Program started MyAttribute created with 15. 15 Program ended 

But don't worry about the performance of attribute constructors. They are the fastest part of reflection :-P

1 Comment

Damn! Tried to do this one in VS 2010 but I'm totally lost without ReSharper XD
4

The metadata in the executable or DLL stores:

  • A metadata token indicating the constructor to call
  • The arguments

When I get to that section of my CLI implementation, I plan to lazy-call the constructor the first time GetCustomAttributes() is called for the ICustomAttributeProvider. If a particular attribute type is requested, I'll only construct the ones required to return that type.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.