C# Static Constructor
In C#, a static constructor is a special type of constructor that is used to initialize the static members of a class before any static methods are called or any static properties are accessed. This guide explores the syntax, usage, and considerations of static constructors in C#.
Syntax
public class MyClass
{
// Static constructor
static MyClass()
{
// Initialization code for static members
}
// Other members of the class
// ...
}
Example
public class Logger
{
// Static variable to track the number of log entries
private static int logCount;
// Static constructor to initialize static members
static Logger()
{
logCount = 0;
Log("Logger initialized.");
}
// Static method to log messages
public static void Log(string message)
{
Console.WriteLine($"[LOG #{++logCount}] {message}");
}
}
class Program
{
static void Main()
{
Logger.Log("Application started.");
}
}
Output
The output will be log messages indicating that the logger is initialized and that the application has started.
Explanation
- A static constructor is declared using the
static
keyword before the constructor definition. - The static constructor is called automatically before any static members are accessed or any static methods are called.
- In the example, the
Logger
class has a static constructor that initializes a static variable and logs a message.
Use
Use a static constructor in C# when:
- You need to perform one-time initialization of static members.
- Initialization code for static members depends on certain conditions.
- You want to ensure that static members are initialized before their first use.
Important Points
- A static constructor does not take any parameters and cannot be called explicitly.
- Only one static constructor is allowed in a class.
- Static constructors are called automatically before any static members are accessed or any static methods are called.
Summary
C# static constructors provide a mechanism for initializing static members of a class before their first use. They are useful for performing one-time initialization tasks and ensuring that static members are in a valid state. Understanding when and how to use static constructors can contribute to writing robust and well-organized C# code.