C# Static Constructors

Summary: in this tutorial, you’ll learn about static constructors and how to use them to initialize static members.

Introduction to the C# static constructors

When creating an instance of a class, the C# compiler automatically calls the constructor. This constructor is called an instance constructor because it creates a new instance and initializes the instance members.

If you use the static keyword to declare a constructor, the constructor becomes a static constructor. Generally, a static constructor initializes static fields and properties.

A static constructor is different from an instance constructor in the following ways:

  • A static constructor uses the static keyword in the declaration.
  • A class can have only one static constructor. And the static constructor cannot have any parameters.
  • A static constructor cannot have an access modifier like public or private.

Like a static method, a static constructor cannot access instance members of a class. Therefore, you cannot use the this keyword inside the static constructor. However, the static constructor can access instance fields and properties.

Note that a class may have both instance and static constructors.

C# static constructor example

The following example defines a class that contains a static constructor:

class RandomNumber
{
    private static Random random;

    static RandomNumber()
    {
        random = new Random();
    }
    public int Get() => random.Next();
}Code language: C# (cs)

How it works.

  • The RandomNumber class contains a static field which is an instance of the Random class.
  • The static constructor creates a new instance of the Random class and assigns it to the random static field.
  • The Get() instance method returns a random integer by calling the Next() method of the random object.

The following program uses the RandomNumber class to generate five random integers:

// Program.cs
RandomNumber random = new();
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(random.Get());
}Code language: C# (cs)

Summary

  • Use C# static constructors to initialize static members.
Was this tutorial helpful ?