What’s the function of a static constructor in a non static class?

Do you use it to initialize static fields on your instance of the non-static type?

Pretty much, except that static fields (or static members of any kind) aren’t associated with instances; they are associated with the type itself, regardless of whether it is a static class or a non-static class.

The documentation lists some properties of static constructors, one of which is:

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

Here, “before” means “immediately before”, and whichever one of those things happens first. This is because a static constructor is only called once per type in a single program execution.


Are there any things to take into consideration when using a static constructor?

Here’s the full list as given by the link above, which should give you an idea of what to expect when using a static constructor:

  • A static constructor does not take access modifiers or have parameters.

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

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Besides making sure you don’t try to access non-static members, since you’re not in an instance constructor, the other main thing you have to consider is that a static constructor is always called at a specific time during program execution. As stated, you cannot control this, other than by controlling when “the first instance is created or any static members are referenced.”

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)