0

I have this simple program, the problem is that the code never reaches TestClassAttribute class. The console output is:

init
executed
end

The Code

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("init");
        var test = new Test();
        test.foo();
        Console.WriteLine("end");
        Console.ReadKey();
    }
    public class TestClassAttribute : Attribute
    {
        public TestClassAttribute()
        {
            Console.WriteLine("AttrClass");
            Console.WriteLine("I am here. I'm the attribute constructor!");
            Console.ReadLine();
        }
    }

    public class Test
    {
        [TestClass]
        public void foo()
        {
            Console.WriteLine("executed");
        }
    }
}
06needhamt
  • 1,555
  • 2
  • 19
  • 38
  • 3
    You never construct an instance of `TestClassAttribute`, e.g. with `new TestClassAttribute()`. – Rob I Jun 26 '13 at 19:56

4 Answers4

3

You should probably read up on How do attribute classes work?.

They aren't instantiated when you create an object that they are applied to, not one static instance, not 1 per each instance of the object. Neither do they access the class that they are applied to..

You can try to get the list of attributes on a class, method, property, etc etc.. When you get the list of these attributes - this is where they will be instantiated. Then you can act on the data within these attributes.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
2

Attributes don't do anything by themselves. They are not even constructed before one asks for attributes on particular class/method.

So to get your code to write "AttrClass" you need to ask for attributes of foo method explicitly.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

Attributes are lazily instantiated. You have to get attribute in order to constructor be called.

var attr = test.GetType().GetMethod("foo")
            .GetCustomAttributes(typeof(TestClassAttribute), false)
            .FirstOrDefault();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
pr3dr46
  • 21
  • 2
0

No, no. Attributes are special. Their constructors aren't run until you use reflection to get to them. They don't need to run then. For example, this small method reflects into the attribute:

public static string RunAttributeConstructor<TType>(TType value)
{
    Type type = value.GetType();
    var attributes = type.GetCustomAttributes(typeof(TestClassAttribute), false);
}

You'll see wherever you call this in your Main the constructor for the attribute will run.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103