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

When static parameterless constructor is called in structure.

4
  • 1
    You can't manually invoke static constructors, they are called automatically when the type is loaded. Commented Aug 14, 2013 at 11:57
  • It's called the first time you ever reference a TestStruct in your code Commented Aug 14, 2013 at 11:57
  • Take a look at this csharpindepth.com/Articles/General/Beforefieldinit.aspx Commented Aug 14, 2013 at 11:59
  • Please see this answer. Commented Aug 14, 2013 at 12:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your valuable answer
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.
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.)

  • 1 Comment

    "when the type is loaded" ... is tricky; it is a lot more subtle and complex than that

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.