A singleton is like the Egg of Columbus. Easy after someone had showed you how to do it. Luckily Jon Skeet had showed us how to use lazy evaluation for thread safety. And an unknown contributor of Great Maps had demonstrated the usage of generics for that purpose. So all that is left for me - is to put it all together.

public sealed class Singleton<T> where T : new()
    private static readonly Lazy<T> instance = new Lazy<T>(() => new T());

    public static T Instance { get { return instance.Value; } }

    private Singleton()

// Create two server objects pointing to the same instance.
Server svr1 = Singleton<Server>.Instance;
Server svr2 = Singleton<Server>.Instance;
- C# In Depth: Implementing the Singleton Pattern in C#
- GMap.NET Singleton Class

0 comment(s) :

Newer Post Older Post Home

Blogger Syntax Highliter