Skip to content

Instantly share code, notes, and snippets.

@soraphis
Last active October 8, 2019 07:34
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 soraphis/c21319d90ed5043c7556f8f7ef27637d to your computer and use it in GitHub Desktop.
Save soraphis/c21319d90ed5043c7556f8f7ef27637d to your computer and use it in GitHub Desktop.
generic version of thread safe singletons based on: https://csharpindepth.com/Articles/Singleton
// ---------------------------------------------------------------------------------------------
// SOME UTILY CLASSES
// ---------------------------------------------------------------------------------------------
public abstract class ThreadSafeSingleton<T> where T : ThreadSafeSingleton<T>, new()
{
static ThreadSafeSingleton(){}
protected ThreadSafeSingleton() { }
public static T Instance { get; } = new T();
}
public abstract class LazyThreadSafeSingleton<T> where T : LazyThreadSafeSingleton<T>, new()
{
protected static readonly Lazy<T> lazy = new Lazy<T>(() => new T());
protected LazyThreadSafeSingleton() { }
public static T Instance => lazy.Value;
}
// ---------------------------------------------------------------------------------------------
// USAGE EXAMPLE
// ---------------------------------------------------------------------------------------------
public sealed class STestClass1 : ThreadSafeSingleton<STestClass1>
{
public readonly int i = 3;
}
public sealed class STestClass2 : LazyThreadSafeSingleton<STestClass2>
{
public readonly int i = 4;
}
class SomeClass {
static void Main(string[] args)
{
Console.WriteLine(STestClass1.Instance.i);
Console.WriteLine(STestClass2.Instance.i);
}
}
// ---------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment