Search code examples
c#.netstatic-constructor

Does every type have static constructor?


According to documentation: A static constructor is called automatically. It initializes the class before the first instance is created or any static members are referenced.

Does it mean that every type (with or without static members) have static constructor? Or static constructor presents in types that have static members or explicitly defined?

Does this type have static constructor that called automatically behind scene?

class Test
 {
    public Test()
    {
        System.Console.WriteLine("Type initialized!");
    }     
 }

Solution

  • Quoting from the documentation, it seems that the answer is NO, only types where you explicitly write a static constructor has one. That's hinted by there two points:

    If you don't provide a static constructor to initialize static fields, all static fields are initialized to their default value as listed in Default values of C# types.

    This suggest that static constructor is not always required and a default behavior is in place by the CLR.

    The presence of a static constructor prevents the addition of the BeforeFieldInit type attribute. This limits runtime optimization.

    Which suggest that the CLR can change its behavior in resopnse to the presence (or not) of a static constructor.

    That said, any class or struct can have a static constructor, regardless it has any static members or not. But it seems that the compiler doesn't automatically generates one if you don't write it.