Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created September 1, 2017 11:43
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 wolf99/c5919299888302288215a79df48a8b1b to your computer and use it in GitHub Desktop.
Save wolf99/c5919299888302288215a79df48a8b1b to your computer and use it in GitHub Desktop.
C# singleton class pattern
namespace Foo
{
/// <summary>
/// A class showing the bolierplate code for a singleton
/// </summary>
public sealed class BoilerplateSingleton // sealed to prevent derivatives adding non-singleton copies
{
// this class is a singleton, this field holds the single instatiated
// object. It is instantiated lazily, only being created when a
// reference to the object is requested via the Instance property
private static readonly Lazy<BoilerplateSingleton> lazy =
new Lazy<BoilerplateSingleton>(() => new BoilerplateSingleton());
/// <summary>
/// Gets a reference to the singleton instance
/// </summary>
public static BoilerplateSingleton Instance { get => lazy.Value; }
// constructor is private because this is a singleton
private BoilerplateSingleton() { }
// rest of class ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment