Updated March 22, 2023
Introduction to Static Constructors in C#
Static constructors in C# are constructors implemented to be invoked only once and only during the creation of the reference for a static member implemented in the class. The primary function for a static constructor is to initialize the static members for the class and only once execution. The static constructor as the name suggests does not allow explicit control to the user but is executed automatically upon the invoke of the instance of the class, Further, the static constructor doesn’t take any parameter or access declaration in its definition, thus it can’t be called directly. Static constructors cannot be inherited or overloaded and only accessible to the CLR (Common Language Runtime).
Features and Uses of Static Constructors in C#
Following are some features and uses of static constructors in c# explained in details:
Features for Static Constructor
The following features describe the static constructor:
- The user does not have any control over the static constructor on runtime. These are predefined in the code before precompiling and the value remains fixed for the entire duration.
- The static constructor operation can be further broken down into two stages i.e. static data members initializing and static action execution which occurs in the sequential order as defined.
- A static method does not have any access modifier in its definitions and hence cannot be called upon by other components in the program.
Uses for Static Constructor
Static constructors find its major use in log programs where it is used to write the parameter entries initialized during each instance. Static constructors are the ideal positions to create database connections as they are loaded first and remain static throughout. In C# programming language the static constructors following the following Syntax.
Syntax:
class ABC
{
//defining the static constructor using the same name as class
static ABC()
{
//constructor specific code comes here
}
}
How Static Constructors Work in C#?
Here are some basic working principle of static constructor in C# which are as follows:
- When a class or an object of the class is created as a struct, constructors are called upon to create the data members associated with the class. These constructors have the same name as the class.
- In order to understand the concept of static constructors, we would first need to understand the concept behind static methods and classes.
- A static class is differentiated from a regular class due to the fact that the static class cannot be instantiated i.e. the new keyword cannot be used for creating the new instance of the class.
- Hence the class cannot be accessed using the new instance and needs to be called upon by the static class name itself. These classes are used to work upon the input fields and operated to create an initial and fixed value of the input parameters.
- A static constructor as the name suggest is used to set up or initialize any static data required at the pre-rendered stages of the class construct. The static constructor is called upon before the first instance of the class is created or the reference is looked upon for any static members.
- Thus one can define static constructors as the first instance of the class that is created in run time, also this is a single occurrence event and is not repeated again.
Examples to Implement Static Constructors
Here are some of the examples of static constructor in C# which are given below:
Example #1
Code:
using System;
namespace HappyConstructor {
class Happy {
//let us declare and initialise the static data members
private static int id = 7;
public static int Id {
get {
return id;
}
}
public static void printVariable() {
Console.WriteLine("Happy.id = " + id);
}
static void Main(string[] args) {
//let us print the value of ID from the class
Happy. printVariable ();
}
}
}
Output:
Explanation: In the above, the static member id is declared for use and initialized to the initial value of 10.
Example #2
Code:
using System;
namespace Happy1Constructor {
class Happy1 {
private static int Id;
//data member (id) is set conditionally here to show actions of a Static constructor
static Happy1 () {
if (Happy1.Id < 10) {
Id = 25;
} else {
Id = 1000;
}
Console.WriteLine("Static Constructor for Class Happy Called..");
}
public static void print() {
Console.WriteLine("Happy1.Id = " + Id);
}
public static void Main(string[] args) {
// the value of Id is displayed as
Happy1.print();
}
}
}
Output:
Explanation: In the example above the constructor is conditionally dependent upon the Happy.cs file generated in example1. Here the static constructor initializes itself. since the value is in the first case the Id field generated is 7 and as per the conditional operator if the value of the field is less than 10 then the value for the Id field for the Happy1 constructor shall be 25. This is a classic example of initializing a static constructor upon the first instance of loading of the class. The static constructor makes use of this feature to preload the input parameters for the program referencing.
Conclusion
A static constructor is used to initialize any static data and or in performance of any particular actions that need to be performed once and only once for the program. This constructor is called upon before any of the objects of the class is initiated or any of the members are loaded on to the run time environment.
Recommended Articles
This is a guide to Static Constructor in C#. Here we discuss how static constructors work in C# along with the syntax, examples and code implementation. You may also look at the following articles to learn more-