Skip to content

Instantly share code, notes, and snippets.

@ravage
Last active September 25, 2020 09:35
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 ravage/833d5b98fbb0d5e721bf7d5c0cbb7072 to your computer and use it in GitHub Desktop.
Save ravage/833d5b98fbb0d5e721bf7d5c0cbb7072 to your computer and use it in GitHub Desktop.
// Not thread safe
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed
public sealed class Singleton {
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
private static Singleton instance = null;
// hide constructor from public interface
private Singleton() {}
public static Singleton Instance {
get {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
}
// Thread safe
public sealed class Singleton {
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly
private static readonly Singleton InstanceHolder = new Singleton();
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
static Singleton() {}
private Singleton() {}
public static Singleton Instance => InstanceHolder;
}
// Thread safe & Lazy
// https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1
public sealed class Singleton {
private static readonly Lazy<Singleton> InstanceHolder = new Lazy<Singleton>(() => new Singleton());
private Singleton() {}
public static Singleton Instance => InstanceHolder.Value;
}
// Generic Singleton
// For the sake of example only since it defeats the singleton purpose (the is no control over T's implementation)
public sealed class Singleton<T> where T : new()
{
private static readonly Lazy<T> InstanceHolder = new Lazy<T>(() => new T());
private Singleton() {}
public static T Instance => InstanceHolder.Value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment