C# Static Constructor with Examples

In c#, Static Constructor is used to perform a particular action only once throughout the application. 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.

 

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.

 

  • Static constructor in c# won’t accept any parameters and access modifiers.
  • The static constructor will invoke automatically, whenever we create a first instance of class.
  • The static constructor will be invoked by CLR so we don’t have a control on 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 c# programming language.

 

class User

  {

     // Static Constructor

     static User()

      {

          // Your Custom Code

       }

  }

If you observe 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 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.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Static Constructor Example Result

 

If you observe 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.

 

This is how we can use static constructor in c# programming language to execute particular action only once throughout the application based on our requirements.

Topics Covered