0Pricing
C# Academy · Lesson

Static Constructors

Initialize static state exactly once.

What Is a Static Constructor?

A static constructor initializes static data for a class. It runs automatically once, before the class is first used, and you never call it directly.

using System;

class App
{
    public static string Version;

    static App()
    {
        Version = "1.0.0";
        Console.WriteLine("Static constructor ran");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(App.Version);
    }
}

Syntax Rules

A static constructor uses the static keyword, has the class name, takes no parameters, and has no access modifier.

using System;

class Config
{
    public static int MaxUsers;

    static Config()
    {
        MaxUsers = 100;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Max: " + Config.MaxUsers);
    }
}

All lessons in this course

  1. Defining Constructors
  2. Constructor Chaining with this
  3. Object and Collection Initializers
  4. Static Constructors
← Back to C# Academy