1

Possible Duplicate:
Why doesn't the CLR always call value type constructors

Found next code in Richter's book (I have simplified it a little bit):

internal struct SomeValType
{
    static SomeValType()
    {
        Console.WriteLine("This never gets displayed");
    }
    public Int32 X;
}

public sealed class Program
{
    public static void Main()
    {
        SomeValType a = new SomeValType { X = 123 };
        Console.WriteLine(a.X);
    }
}

Output:

123

Can't understand why WriteLine in static constructor nevel calls. Looked at ILDasm - constructor code and calling of method are present. If I add any static variable to SomeValType and init it in constructor then WriteLine calling correctly.

Can someone explain, please, behavior in such situation? Thanks.

Community
  • 1
  • 1
kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
  • I tried making X static and assigning it in the constructor. This made the console output appear as expected. Same thing happened if I removed X entirely and threw in a static method that I called in Main(). Perhaps static constructors aren't invoked unless a static method or member is called/accessed? – Martin Törnwall May 01 '11 at 10:29

2 Answers2

1

Probably because you're never accessing a real constructor nor a static field.

The default constructor of value types is special. It's just an initialization to binary the default value of all fields(i.e. binary zero the whole struct)

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

From MSDN:

  • A static constructor is called automatically to initialize the class [emphasis mine] before the first instance is created or any static members are referenced.

It seems that the word class is the key here. Making SomeValType a class results in a static constructor invocation upon creating the first instance of the type as stated above. When it is a struct, however, it seems you need to access a static field or call a static method for this behavior to be triggered. Is this a bug or is it intended?

Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35