In this article we are going to discuss about static constructor with examples in C#.
A static constructor is used to initialize static members of the class. It is called only once, when the class is first loaded. If we declare a constructor as static, It will be called automatically before the first instance is created.
The below are the following features of Static Constructor.
Here is the syntax for defining a static constructor.
class MyClass
{
static MyClass()
{
// Initialization code
}
}
Example
The following code define the static constructor.
using System;
namespace delegateproject
{
public class Person
{
// Static Constructor
static Person()
{
Console.WriteLine("Called Static Constructor");
}
}
class Program
{
static void Main()
{
// Usage
Person person = new Person();
Console.ReadLine();
}
}
}
Output
Static Constructor - Order of Execution
The static constructor is executed before any static member is accessed or any instances of the class are created.
Example
using System;
namespace delegateproject
{
public class Person
{
// Instance constructor
public Person()
{
Console.WriteLine("Instance constructor called.");
}
// Static Constructor
static Person()
{
Console.WriteLine("Called Static Constructor");
}
}
class Program
{
static void Main()
{
// Usage
Person person = new Person();
Console.ReadLine();
}
}
}
Output
Static Constructor - Access the Static Member
Consider the following example that demonstrates a static constructor in use:
using System;
namespace delegateproject
{
public class Person
{
public static int StaticField;
// Instance constructor
public Person()
{
Console.WriteLine("Instance constructor called.");
}
// Static Constructor
static Person()
{
StaticField = 10;
Console.WriteLine("Called Static Constructor");
}
public static void Display()
{
Console.WriteLine($"StaticField: {StaticField}");
}
}
class Program
{
static void Main()
{
// Accessing the static member for the first time
Person.Display();
Person person = new Person();
Console.ReadLine();
}
}
}
Output
Static constructors are used for: