0

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:

enter image description here

Questions:

  1. Why this's value is the value that gets returned from ToString?

  2. MyFirst has no value. On what moment it will [EDIT: i.e., what method in System.CustomAttribute initializes this property]? (Couldn't see it happening with the debugger, I don't know why).

Community
  • 1
  • 1
OfirD
  • 9,442
  • 5
  • 47
  • 90

1 Answers1

0

ToString is really designed (read: was designed) as a debugging tool and that is why it shows up as the local value in the Locals window.

It appears that any names parameters to an attribute are assignments after the constructor is run. Loosely this is how I think the compiler interprets that:

TestClassAttribute instance = new TestClassAttribute();
instance.First = "customized";
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445