Function of a Static Constructor in Non Static Class

Static Constructor

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.

There are some things to take into consideration when using a static constructor.

Here's the detail which should give you an idea of what to expect when using a static constructor.

  1. A static constructor does not take access modifiers or have parameters.
  2. Declared by prefixing a static keyword to the constructor definition.
  3. It can not take access modifiers or have any parameters.
  4. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  5. A static constructor cannot be called directly.
  6. The user has no control on when the static constructor is executed in the program.
  7. 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.
  8. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  9. 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."

Example

public class ConstStatic
{
    public ConstStatic()
    {
        Console.WriteLine("non-static");
    }

    static ConstStatic()
    {
        Console.WriteLine("static");
    }
}

Thank you for reading, and I hope this post has helped you with a better understanding of a static constructor in a non static class.

Happy Coding !!!