Skip to content

Instantly share code, notes, and snippets.

@alexnum
Forked from OmegaExtern/Singleton Pattern.cs
Created September 13, 2022 16:37
Show Gist options
  • Save alexnum/2f5a6ad6c3a5016658549513db7fcf9f to your computer and use it in GitHub Desktop.
Save alexnum/2f5a6ad6c3a5016658549513db7fcf9f to your computer and use it in GitHub Desktop.
Singleton Pattern in C#.
#region Singleton Pattern
// NOTE: The class is marked as sealed to prevent the inheritance of the class (i.e. use it as base/super class).
internal sealed class Singleton
{
private static readonly object SingletonSyncRoot = new object();
private static volatile Singleton _instanceSingleton;
// NOTE: Default/Parameterless constructor is private to prevent instantiation of the class.
private Singleton()
{
}
public static Singleton Instance
{
get
{
// Double-checked locking pattern.
if (_instanceSingleton != null)
{
return _instanceSingleton;
}
lock (SingletonSyncRoot)
{
return _instanceSingleton ?? (_instanceSingleton = new Singleton());
}
}
}
}
// NOTE: The class is marked as sealed to prevent the inheritance of the class (i.e. use it as base/super class).
internal sealed class EagerSingleton
{
// NOTE: Default/Parameterless constructor is private to prevent instantiation of the class.
private EagerSingleton()
{
}
// CLR eagerly initializes static member when the class is first used
// CLR guarantees thread-safety for static initialization
public static EagerSingleton Instance
{
get;
} = new EagerSingleton();
}
#endregion Singleton Pattern
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment