Created
September 1, 2017 11:43
-
-
Save wolf99/c5919299888302288215a79df48a8b1b to your computer and use it in GitHub Desktop.
C# singleton class pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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