In c#, Static Constructor is useful to perform a particular action only once throughout the application. If we declare a constructor as static, it will be invoked only once, irrespective of the number of class instances. It will be called automatically before the first instance is created.
Generally, in c# the static constructor will not accept any access modifiers and parameters. In simple words, we can say it’s parameterless.
The following are the properties of static constructor in the c# programming language.
Following is the syntax of defining a static constructor in the c# programming language.
If you observe the above syntax, we created a static constructor without having any parameters and access specifiers.
Following is the example of creating a static constructor in c# programming language to invoke the particular action only once throughout the program.
If you observe the above example, we created a static constructor and a default constructor. Here the static constructor will be invoked only once for the first instance of a class.
When you execute the above c# program, we will get the result below.
If you observe the above result, for the first instance of a class, both static and default constructors execute. For the second instance of a class, only the default constructor has been executed.
This is how you can use a static constructor in the c# programming language to execute particular actions only once throughout the application based on your requirements.