C# Static Constructor with Examples

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.

 

  • Static constructor in c# won’t accept any parameters and access modifiers.
  • The static constructor will invoke automatically whenever we create the first instance of a class.
  • CLR will invoke the static constructor, so we don’t have control over the static constructor execution order in c#.
  • In c#, only one static constructor is allowed to create.

C# Static Constructor Syntax

Following is the syntax of defining a static constructor in the c# programming language.

 

class User
{
    // Static Constructor
    static User()
    {
       // Your Custom Code
    }
}

If you observe the above syntax, we created a static constructor without having any parameters and access specifiers.

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.

 

using System;

namespace Tutlane
{
     class User
     {
        // Static Constructor
        static User()
        {
           Console.WriteLine("I am Static Constructor");
        }
        // Default Constructor
        public User()
        {
           Console.WriteLine("I am Default Constructor");
        }
     }
     class Program
     {
         static void Main(string[] args)
         {
             // Both Static and Default constructors will invoke for first instance
             User user = new User();
             // Only Default constructor will invoke
             User user1 = new User();
             Console.WriteLine("\nPress Enter Key to Exit..");
             Console.ReadLine();
         }
     }
}

If you observe the above example, we created a static constructor and 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 as shown below.

 

C# Static Constructor Example Result

 

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 action only once throughout the application based on your requirements.