C# Singleton Pattern Implementation Guide

In C#, the singleton design pattern can be implemented in two ways.

  1. Hungry singleton pattern
public class Singleton
{
    private static Singleton instance = new Singleton();

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}
  1. Lazy Singleton Pattern
public class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

Both implementations ensure that only one instance object exists throughout the entire application and provide a global access point to obtain that instance. When using the singleton pattern, it is important to consider thread safety, which can be ensured by techniques such as locking or using double-checking.

bannerAds