views:

470

answers:

3

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?

+11  A: 

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.

Fredrik Mörk
+1 damn; that'll teach me to fire up visual studio for a question that is already 6 minutes old :-)
Wim Coenen
Note that the constructor is run multiple times if you call GetCustomAttributes multiple times.
Wim Coenen
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).
Fredrik Mörk
Anyone know _why_ the attribute objects aren't cached?
Matt Howells
@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.
Fredrik Mörk
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.
Guillaume
+1  A: 

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.

280Z28
+3  A: 

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

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