CodeBlanks Logo Icon CodeBlanks

Singleton

C# course · Advanced · Lesson 61/83

Learn to write a single-instance class with the Singleton pattern.

Singleton pattern

Singleton is a pattern that guarantees a class has only one instance. Three pieces make it work: a private constructor (private Config()) that blocks external new, a static field holding the single instance (private static readonly Config _instance), and a static property exposing it (public static Config Instance).

Marking the class sealed prevents subclasses from creating a second instance. Static fields in C# are lazily initialized on first access, so a basic Singleton needs no extra locking.

sealed and lazy initialization

The sealed keyword seals the class; subclasses cannot create new instances. This protects the single-instance guarantee from being broken through derivation. In C#, static fields are created the first time they are accessed; this is lazy initialization.

An expression-bodied property is a concise way to return the single instance: public static Config Instance => _instance;. The => arrow is a one-line expression that computes the property value.

Exercise Define the Singleton Config class

Define a sealed class Config. Add a private constructor (private Config()), a static readonly _instance field, a public static Config Instance property, and a string Greet() method. In Main, print Config.Instance.Greet().

Show example solution
Console.WriteLine(Config.Instance.Greet());
Example solution:
using System;

sealed class Config
{
    private static readonly Config _instance = new Config();
    public static Config Instance => _instance;
    private Config() { }
    public string Greet() => "Merhaba";
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Config.Instance.Greet());
    }
}

Test yourself

  1. What is the main goal of the Singleton pattern?

    • Ensure a single instance and provide global access
    • Create many instances
    • Force inheritance
    • Hide static methods
    Show answer

    Ensure a single instance and provide global access — Correct. Singleton guarantees one instance and exposes it via a static property.

  2. Complete the expression-bodied property

    public static Config Instance ____ _instance;
    Show answer
    public static Config Instance => _instance;
  3. Why use a private constructor in Singleton?

    • To make the class static
    • To make it run faster
    • To prevent external new from creating another instance
    • To hide inherited methods
    Show answer

    To prevent external new from creating another instance — Correct. A private constructor prevents external new from creating more instances.

All lessons in Advanced