How to call a static constructor or when static constructor is called in C#?


Static constructor are called automatically before the first instance is created or any static members are referenced.

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only.

In c#, only one static constructor is allowed to create

Static constructors have the following properties −

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

  • A class or struct can only have one static constructor.

  • Static constructors cannot be inherited or overloaded.

  • A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

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

Example

class Program{
   static Program(){
      // Your Code
   }
   static void Main(){
      Console.ReadLine();
   }
}

Updated on: 04-Aug-2020

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements