I'm trying to understand how custom attributes work. I have the following code (Which is mostly based on this SO answer):
class Test
{
public static void Main()
{
Console.WriteLine("before class constructor");
var test = new TestClass();
Console.WriteLine("after class constructor");
Attribute[] attributes = Attribute.GetCustomAttributes(test.GetType());
}
}
public class TestClassAttribute : Attribute
{
public TestClassAttribute()
{
Second = "hello";
Console.WriteLine("I am here. I'm the attribute constructor!");
}
public String First { get; set; }
public String Second { get; set; }
public override String ToString()
{
return String.Format("MyFirst: {0}; MySecond: {1}", First, Second);
}
}
[TestClass(First = "customized")]
public class TestClass
{
public int Foo { get; set; }
}
I put a breakpoint on Main
's last line, and using the debugger I dived into the source code until the TestClassAttribute
constructor got called (happens inside the unsafe
overload of CustomAttribute.GetCustomAttributes
). Once passed the constructor's first line, I have the following content on the Locals window:
Questions:
Why
this
's value is the value that gets returned fromToString
?MyFirst
has no value. On what moment it will [EDIT: i.e., what method inSystem.CustomAttribute
initializes this property]? (Couldn't see it happening with the debugger, I don't know why).