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"); } } } 
1
  • 3
    You never construct an instance of TestClassAttribute, e.g. with new TestClassAttribute(). Commented Jun 26, 2013 at 19:56

4 Answers 4

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.

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

Comments

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.

Comments

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(); 

Comments

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.

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.