Is there a difference between static constructors of structures and classes and their calls in C #?

1 answer 1

There is a fairly well-known misconception that static constructors do not work for structures. But it is not. they just work a little differently than for the classes. The difference, for example, is this: for reference types (including classes), the static constructor is called before the first instance of the class is created. For structures, it is called when accessing static members of the structure. Example:

struct Foo { static Foo() { Console.WriteLine("from static Foo"); } public static int Bar = 10; } class FooClass { static FooClass() { Console.WriteLine("from static FooClass"); } public static int Bar = 10; } // перед созданием экземпляра вызовется статический конструктор, //который напечатает текст "from static FooClass" var fooCl = new FooClass(); // а здесь статический конструктор вызван не будет var foo = new Foo(); // // он будет вызван здесь, если раскомментировать следующую строку //Foo.Bar = 11; 

And now a little explanation for this witch. The fact is that type-values ​​in C # (and structures including) have a lot of differences from reference types (including classes). One of these differences is the work of the default constructor. For structures in order to save performance (if I'm not mistaken) when calling the default constructor, all fields are initialized with default values. Accordingly, the creation of an instance as such does not occur, whereas the static constructor is called when the instance is first instantiated. But if you add a constructor with arguments to the structure (you can’t add your default constructor) and create an instance of the structure through this constructor, the static constructor will be called. Example:

 struct Foo { static Foo() { Console.WriteLine("from static Foo"); } public Foo(int i) { } } // здесь произойдёт вызов статического конструктора, // так как происходит "обычное" создание экземпляра var foo = new Foo(1); 
  • 2
    "have a lot of differences from significant types" - from the reference ones. - Qwertiy
  • @Qwertiy, of course, thanks - DreamChild
  • five
    For reference types, the static constructor is not only called before the first instance is created. When referring to any static field of the class, the static constructor will also be called first, although no one has created instances of the class) - Trymount
  • @Trymount, thanks! reassured! I was really nervous ... - 4per