Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Created April 17, 2026 20:07
Show Gist options
  • Select an option

  • Save peteraritchie/bf2e671d1fc0b0796b072500bd83a3dc to your computer and use it in GitHub Desktop.

Select an option

Save peteraritchie/bf2e671d1fc0b0796b072500bd83a3dc to your computer and use it in GitHub Desktop.
A base class to implement singleton pattern in C#
/// <summary>
/// A base class that implements a singleton pattern.
/// <example>
/// Declaring a singleton class:
/// <code>
/// public class Singleton : SingletonBase&lt;Singleton&gt;
/// {
/// public int Number { get; set; }
/// }
/// </code>
/// Getting an instance:
/// <code>
/// var instance = Singleton.Instance;
/// </code>
/// </example>
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class SingletonBase<T> where T : new()
{
private static readonly Lazy<T> LazyInstance = new(() => new T());
public static T Instance => LazyInstance.Value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment