Static Constructor in C#

Static Constructor in C#

A static function is used to initialise any static data or to make a single-use action. Before the first instance is created or any static members are accessed, it is automatically called.

Points to remember about Static Constructor:

  1. There are no access modifiers or arguments in a static function.
  2. There can only be one static function per class or struct.
  3. Inherited or overloaded constructors are not allowed.
  4. A static function can only be invoked by the common language runtime and cannot be called directly (CLR). It’s started on its own.
  5. The user has no control over when the program’s static function is called.
  6. In a single application domain, the runtime invokes a static function no more than once. A static function is called automatically.
  7. If you don’t provide a static function to initialise them, all static fields are set to their default value.
  8. If a static function throws an exception, the runtime does not recall it, and the type stays uninitialized throughout the application domain.
  9. Because there is a static function, the BeforeFieldInit type attribute cannot be added. This limits the amount of time that can be optimised while running.
  10. Only as part of their declaration or in a static function may static read-only fields be assigned.
  11. The runtime only calls the static function once in a single application domain.
namespace StaticConstructor
{
  class Addition
  {
    static Addition()
    {
        Console.WriteLine("Static Constructor called");
    }

    public Addition()
    {
        Console.WriteLine("Instance Constructor called");
    }
}
class Program
{


    static int Main(string[] args)
    {

        Addition obj1 = new Addition();
        Addition obj2 = new Addition();

        return 0;
    }
}
}

Output:

Static Constructor called
Instance Constructor called
Instance Constructor called