Skip to content

Instantly share code, notes, and snippets.

@chrismoutray
Last active March 29, 2018 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismoutray/3f66c5e4bea0ff862d9dcbf232c704d9 to your computer and use it in GitHub Desktop.
Save chrismoutray/3f66c5e4bea0ff862d9dcbf232c704d9 to your computer and use it in GitHub Desktop.
example Singleton implementation using Lazy object

how best to create singleton class

It is simplest, thread-safe solution with lazy initialization, that everyone can understand.

Example pull from here https://rubikscode.net/2017/06/11/different-ways-to-implement-singleton-in-net-and-make-people-hate-you-along-the-way/ But also see this Jon Skeets http://csharpindepth.com/Articles/General/Singleton.aspx#lazy

  • don't do if null check
  • don't use locks
  • use lazy and static class / static constructor
namespace SingletonExamples
{
    /// <summary>
    /// Solution using Lazy implementation.
    /// </summary>
    public class SingletonLazy
    {
        private static readonly Lazy<SingletonLazy> instance =
        new Lazy<SingletonLazy>(() => new SingletonLazy());

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

        private SingletonLazy()
        {
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment