Static constructor C# Example – Learn how to create a static constructor in C# programs with example and when constructors get called and its important points.

Important Points about Static constructor in C# programming

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor cannot be called directly.

Syntax

class Car
    {
         // Static constructor 
        static Car()
        {
              Console.WriteLine(" Static Constructor..."); 
        }
        
    }

In below C# source code example, when we create an object Maruti , For example, “Car maruti = new Car();” first the static constructor called automatically ,then default constructor will be called automatically. You may read how to create class and object in C# with example

Similarly, when we create object Honda, then again only default constructor will be called. Means, As many times as you create an object of the class using new keyword, only at the time of first object creation static constructor will be called and the default constructor will get called every time automatically / implicitly.

Example of how to create a static constructor in C#

/*
    * Example of static constructor in C#
 */
 
    class Car
    {
        static Car()// Static constructor 
        {
              Console.WriteLine(" Static Constructor..."); 
        }
        public Car()
        {
            Console.WriteLine(" Default Constructor..."); 
        }
 
        public void run()
        {
            Console.WriteLine("Car is running...");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //When we create an object, the consturctor of the 
            //class will be called automatically.
            //A static Constructor is called automatically to initialize the class beore the first instance is created 
            //or any static members are referenced.
            Car maruti = new Car();
            maruti.run();
 
            Car honda = new Car();//It will also call constructor of the class
            honda.run();
        }
    }

Output
Static Constructor…
Default Constructor…
Car is running…
Default Constructor…
Car is running…

Related Posts