Static Constructor in C#

Introduction

This article explains the “Static Constructor ” in C#. There is the possibility in C# to add the static no-parameter constructor for a class. It will be executed only once, unlike the normal (or you can say the instance) constructor that is executed whenever the object is created.

Example

Class DemoClass  
{  
    Static DemoClass()  
    {  
        //code inside this constructor  
    }  
}  

The Static Constructor is invoked at most once and is always executed just before any reference for that class is created in our code.

Uses of Static Constructor

It is basically used to initialise the static fields and properties of the class. It can be used mainly where, in our program, we want to do something before any reference for the class is created, like changing the background of the application.

There should at most one Static Constructor in a class and also Static Constructor can't take any parameters.

Example

We will write a simple Console C# program that helps you to understand the uses of a Static Constructor in a program.

In this program we will change the Background of our application based on the weekdays.

Like in the weekend (Saturday & Sunday) it should be Blue and in weekdays it should be any other color, say Black.

Since we are doing it in a console and to make it  simpler, let's just set the color in a static field and show the color type (Blue or Black) in the console window.

Agenda for Static Constructor

  • In Visual Studio create a new console C# program
  • Add a Class
  • Add a static Constructor in the Class
  • Show the value from Main Program

Step 1. In Visual Studio create a new C# Console Project as in the following.

Creating Console Application

Step 2. In the Solution Explorer window, right-click on the solution and add a class.

I have here added a class named “ColorChoice” in my project.

Adding Class in Application

Step 3. We will use the builtin .Net color property, for this we need to have add a reference “System.Drawing.dll” to our project.

Go to the Solution Explorer window and right-click on the References and select "Add Reference...". In the Reference Window search for “System.Drawing” add it to your project.

Adding Reference

Add Drawing Dll Reference

Step 4. In the class that we have already added to our project, add a static constructor and static readonly fields.

Also be sure to add the following using Directives.

using System.Drawing;  

Add the following line of code to “ColorChoice.cs”

namespace StaticConstructorDemo  
{  
    class ColorChoice  
    {  
        public static readonly Color MyColor;  
        static ColorChoice()  
        {  
            //Getting the Current Date using DateTime Class  
            DateTime currentDate = DateTime.Now;  
  
            //Checking the Weekend as it is Saturday or Sunday  
            if(currentDate.DayOfWeek==DayOfWeek.Saturday|| currentDate.DayOfWeek==DayOfWeek.Sunday)  
            {  
                //If the Current Date is Saturday or Sunday  
                //then set the readonly field 'MyColor' to Blue  
                MyColor = Color.Blue;  
            }  
              
            //Days Other than Weekends(i.e other than Staurday or Sunday)  
            else  
            {  
                //If it is not weekend  
                //set the field 'MyColor' to Black  
                MyColor = Color.Black;  
            }              
        }  
    }      
}  

Here in our code we have used the readonly field because a readonly field can only be initialised inside a constructor.

Also we have used a Static Constructor that is the Color Choice based on the weekdays yhat will be generated before any refereznce to the class is created.

Step 5. Now go the Main file in the project (Program.cs file) and add the following line of code

namespace StaticConstructorDemo  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //Calling the Static Constructor of the Class  
            //and Show the Result in the Console Window  
            Console.WriteLine("My Color Choice is:" + ColorChoice.MyColor.ToString());  
            Console.ReadKey();              
        }  
    }  
}  

Here you can see that we have called the Static Constructor of the class without making any reference to the class.

Compile and Run the project. You will see the following output

Ouput in Console App

Since it is not the weekend (depending on my system time and date, it is currently Thursday), so it is showing the color choice for other than weekends that we had set in our code as Black.

That's all for this article. I hope you have understood the concept of a “Static Constructor” very clearly.

If you have any query or suggestions , please feel free to comment.

I am including the source code also. Thanks.


Similar Articles