In this article we will explain how to use Static Constructor or what is Static Constructor in c# or how to use Static Constructor Or how to invoke Static Constructor in c# with example.
The Static Constructor in c# is used to perform a particular action that needs performed once only. If we declare a constructor as static, then it will be invoked only once irrespective of number of class instances and it will be called automatically before the first instance is created or any static members are referenced.
Generally, in c# the static constructor will not accept any access modifiers and parameters. In simple words we can say it’s a parameter less.
Following are the properties of static constructor in c# programming language.
1. A static constructor does not take access modifiers or have parameters.
2. A static constructor is called automatically to initialize the class before the first instance is Created or any static members are referenced.
3. A static constructor cannot be called directly.
4. The user has no control on when the static constructor is executed in the program.
5. 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.
6. The static constructor will be invoked by CLR so we don’t
have a control on static constructor execution order in c#.
7. In c#, only one static constructor is allowed to create.
C# Static Constructor Example
Following is the example of creating a static constructor in c# programming language to invoke the particular action only once throughout the program.
public class Customer
Console.WriteLine("I am Static Constructor");
Console.WriteLine("I am Default Constructor");
public class Program
public static void Main(string args)
// Both Static and Default constructors will invoke for first instance
Customer Customer = new Customer();
// Only Default constructor will invoke
Customer Customer1 = new Customer();
Console.WriteLine("\nPress Enter Key to Exit..");
If you see above example, we created a static constructor and default constructor. Here the static constructor will be invoked only once for the first instance of class.
If you see above result, for the first instance of class both static and default constructors execute and for the second instance of class only default constructor has executed.
In this article you understood, how you
can use static constructor in c# programming language to execute particular
action only once throughout the application based on your requirements.
I hope ti will help to you after reading.