C# Singleton


There are a number of ways to implement the Singleton pattern, and most will work well. This is the easiest implementation I can think of, making use of the various language features and the .NET Framework.

public sealed class Singleton : ICloneable {
    // Ensure lazy loading
    private static readonly Lazy<Singleton> Lazy =
        new Lazy<Singleton>(() => new Singleton());
 
    public static Singleton Instance => Lazy.Value;
 
    private Singleton() { }
 
    // Prevent cloning
    public object Clone() => throw new NotImplementedException();
}

I’m using the Lazy the class for the lazy loading, very easy. The readonly modifier ensures the Instance property cannot be assigned to after the first call to Instance. The private parameterless constrcutor ensures that you cannot create or new up an instance of the Singleton class. Finally, by implementing then ICloneable interface, you can prevent cloning using the MemberwiseClone method of the Object class.

var s = Singleton.Instance;
var s1 = s.Clone();

Console.WriteLine(s.GetHashCode());
Console.WriteLine(s1.GetHashCode());

Now you’ll see one hascode printed in the console, but the second call will throw an exception. You could of course choose not to implement the ICloneable interface, but then it wll be possible to create an extension method, like this:

public static class ObjectExtensionMethods {
    public static T Clone<T>(this T o) {
        var instance = o.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance |
            System.Reflection.BindingFlags.NonPublic);
 
        return (T) instance?.Invoke(o, null);
    }
}

However, this will fail if you do implement the ICloneable interface.

Advertisements