Static Constructor in C#

Introduction

This article explains the “Static Constructor ” in C#.

Description

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.

Code Structure

  1. Class DemoClass  
  2. {  
  3.     Static DemoClass()  
  4.     {  
  5.         //code inside this constructor  
  6.     }  
  7. }  

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

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

  • 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:

  1. using System.Drawing;  
Add the following line of code to “ColorChoice.cs”:
  1. namespace StaticConstructorDemo  
  2. {  
  3.     class ColorChoice  
  4.     {  
  5.         public static readonly Color MyColor;  
  6.         static ColorChoice()  
  7.         {  
  8.             //Getting the Current Date using DateTime Class  
  9.             DateTime currentDate = DateTime.Now;  
  10.   
  11.             //Checking the Weekend as it is Saturday or Sunday  
  12.             if(currentDate.DayOfWeek==DayOfWeek.Saturday|| currentDate.DayOfWeek==DayOfWeek.Sunday)  
  13.             {  
  14.                 //If the Current Date is Saturday or Sunday  
  15.                 //then set the readonly field 'MyColor' to Blue  
  16.                 MyColor = Color.Blue;  
  17.             }  
  18.               
  19.             //Days Other than Weekends(i.e other than Staurday or Sunday)  
  20.             else  
  21.             {  
  22.                 //If it is not weekend  
  23.                 //set the field 'MyColor' to Black  
  24.                 MyColor = Color.Black;  
  25.             }              
  26.         }  
  27.     }      
  28. }  
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 reference 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:
  1. namespace StaticConstructorDemo  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             //Calling the Static Constructor of the Class  
  8.             //and Show the Result in the Console Window  
  9.             Console.WriteLine("My Color Choice is:" + ColorChoice.MyColor.ToString());  
  10.             Console.ReadKey();              
  11.         }  
  12.     }  
  13. }  
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.