singleton pattern in csharp

The Singleton pattern is a creational design pattern that restricts the instantiation of a class to one instance and provides a global point of access to that instance.

Here's an example of how to implement the Singleton pattern in C#:

main.cs
public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
468 chars
25 lines

In this implementation, the Singleton class is marked as sealed to prevent inheritance. The class has a private static variable instance which stores the single instance of the class. The padlock object is used to synchronize threads and avoid race conditions.

The class has a private constructor to prevent direct instantiation from outside the class. The only way to obtain the single instance is through the Instance property, which returns the instance variable after creating it if it hasn't been created already.

This implementation provides a thread-safe way of creating a single instance of the Singleton class, without the need for locks on every access to Instance.

gistlibby LogSnag