In C#, a static constructor is a unique form of constructor responsible for initializing static fields within a class. It can also execute specific tasks that need to happen just once. This constructor is triggered automatically prior to the creation of the initial instance or the referencing of any static member. Additionally, it guarantees that all class-level data is fully initialized before being accessed.
The CSS code snippet shown below defines the styling for a placeholder diagram. It includes a background gradient, border radius, padding, margin, and text alignment properties. The diagram consists of an icon and accompanying text, both styled with specific font sizes and colors.
Syntax:
It has the following syntax:
class ClassName
{
//static constructor
static ClassName()
{
// Initialization code here
}
}
In this format;
- ClassName: Denotes the title of the class.
- Static ClassName: Represents the static constructor of the class.
C# Static Constructor Example
Let's consider an instance to demonstrate the static constructor in C#.
Example
using System;
class C# Tutorial
{
public static string message;
// Static constructor
static C# Tutorial()
{
message = "Hello! this is a static constructor.";
Console.WriteLine("Static constructor executed.");
}
public static void ShowMessage()
{
Console.WriteLine(message);
}
}
class Program
{
static void Main()
{
// Calling static method
C# Tutorial.ShowMessage();
}
}
Output:
Static constructor executed.
Hello! this is a static constructor.
Explanation:
In this instance, we are examining a C# Tutorial where a static field (message) and a static constructor are implemented. The static constructor is invoked automatically just once, prior to accessing any class member. Upon calling the ShowMessage method within the Main function, the static constructor is activated initially, the initialization message is printed, followed by displaying the static field's value.
Remember the following key points:
There are several points to remember about a static constructor in C#. Some of them are as follows:
- Static constructor executes automatically before accessing static members or creating the initial object.
- It doesn't have any parameters or access modifiers .
- The user cannot specifically invoke it.
- The execution is handled by the runtime. Therefore, we have no influence over the timing.
- Static data is only initialized once, which makes it ideal for single-use.
- If any static field initializers are present, they execute before the static constructor.
- It only runs once during the program's lifetime, regardless of how many times the class is accessed.
- A class can contain only one static constructor.
- It is mainly utilized to initialize static fields of a class.
- It cannot be inherited or overloaded.
How Static Constructors Work in C#?
In the C# programming language , a static constructor is a type of constructor that is commonly utilized to initialize the static members of a class. It is automatically executed only once by the CLR (Common Language Runtime) , before the class is accessed for the first time, either via creating an object or calling a static member. There are several steps that can help us understand the working of a static constructor in C#.
- Static Member Initialization: Runtime activates static constructors for member initialization. They run before any static members are used to ensure that they have been properly initialized and are ready to be used.
- Execution Timing: The static constructor is only called once, when the class is first used, either by accessing a static member or creating an object. However, because the exact timing of execution is not guaranteed, we should avoid writing code that is dependent on a specific order.
- Exception Handling: The runtime does not handle exception handling if it throws an exception. As a result, the type is rendered unusable for the rest of the application's existence.
C# Static Constructor Example using Object Creation
Let's consider an example to demonstrate the static constructor through object instantiation in C#.
Example
using System;
public class Account
{
public int id;
public String name;
public static float rateOfInterest;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
static Account()
{
rateOfInterest = 9.5f;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+rateOfInterest);
}
}
class C# Tutorial
{
public static void Main(string[] args)
{
Account acc1 = new Account(101, "Jhonson");
Account acc2 = new Account(102, "Smith");
acc1.display();
acc2.display();
}
}
Output:
101 Jhonson 9.5
102 Smith 9.5
Explanation:
In this instance, we are examining an Account class containing a static constructor that sets the static field rateOfInterest to 9.5f. Subsequently, the static constructor is automatically invoked just once before the initial object of the class is instantiated. Upon creating two objects (acc1 and acc2), both objects inherit the identical rateOfInterest value, showcasing their information using the shared interest rate.
C# Static Constructor Example with Single Execution
Let's consider an illustration to demonstrate the static constructor with a single execution in C#.
Example
using System;
class Login
{
public static string logType;
static Login()
{
logType = "INFO";
Console.WriteLine("Static constructor is successfully executed.");
}
public static void Log(string message)
{
Console.WriteLine($"[{logType}]: {message}");
}
}
class C# Tutorial
{
static void Main()
{
Login.Log("Application has started");
Login.Log("Performing tasks");
Login.Log("Application has ended");
}
}
Output:
Static constructor is successfully executed.
[INFO]: Application has started
[INFO]: Performing tasks
[INFO]: Application has ended
Explanation:
In this instance, we are examining a Login class that contains a static constructor responsible for setting the static field logType to "INFO". The static constructor is triggered just once, prior to the class being accessed for the initial time. Subsequent invocations of the Log method will utilize the initially set value of logType, leading to consistent output. The outcome is then displayed on the console.
Conclusion
In summary, static constructors in C# are essential for initializing static members and performing initialization tasks once before using any class instance or static member. Their automatic and singular execution ensures uniform initialization and eliminates the need for manual triggering by the developer.
C# Static Constructor FAQS
A static constructor in C# cannot be given parameters.
In C# programming, static constructors are unable to take parameters since they are automatically called instead of being triggered by the user.
A static constructor in C# executes only once before any instances of the class are created.
In C#, a static constructor runs automatically just once during the application's lifespan. Its purpose is to guarantee that static members get initialized only once per type.
No, a static constructor cannot be explicitly called in C#.
No, it is triggered automatically by the runtime and cannot be called manually. Users do not have control over the execution of the process.
4) When is a static constructor executed in C#?
It happens prior to accessing static members or instantiating the initial object, guaranteeing proper preparation of static data before utilization.
5) Is it possible for a static constructor to include access modifiers like public or private?
No, access modifiers or parameters are not utilized in static constructors. They inherently remain private to the runtime environment.