0
struct TestStruct
{        
    static TestStruct()
    {
        Console.WriteLine("TestStruct");
    }
}

When static parameterless constructor is called in structure.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Prabhakaran Parthipan
  • 4,193
  • 2
  • 18
  • 27

2 Answers2

7

To invoke it explicitly but safely (once-only, without needing to worry about whether it exists, etc):

System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(
    type.TypeHandle);

However:

When static parameterless constructor is called in structure.

If you mean "when will the runtime execute it" - the only safe answer is when it needs to - the exact details are very complex, and change between runtimes. It would be unwise to depend on the exact timing of this. However, it is guaranteed to execute before you (for example) attempt to access any static fields.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thank you for your valuable answer – Prabhakaran Parthipan Aug 14 '13 at 12:20
  • It may be worthwhile to note that while it's not possible to access a class instance field before the class static constructor has run, that is not true of structure instance fields. Class instance fields don't exist until the containing instance is created, which in turn won't happen until after the class constructor has run, but structure fields can come into existence without the type's involvement, and once they exist they can be accessed--again without the type's involvement. – supercat Aug 14 '13 at 20:09
0

Static constructors are called automatically by the runtime.

The specification details when they are called:

11.3.10 Static constructors

The execution of a static constructor for a struct type is triggered by the first of the following events to occur within an application domain:

  • A static member of the struct type is referenced.
  • An explicitly declared constructor of the struct type is called.

    The creation of default values (§11.3.4) of struct types does not trigger the static constructor. (An example of this is the initial value of elements in an array.)

  • Lee
    • 142,018
    • 20
    • 234
    • 287