Created
April 17, 2026 20:07
-
-
Save peteraritchie/bf2e671d1fc0b0796b072500bd83a3dc to your computer and use it in GitHub Desktop.
A base class to implement singleton pattern in C#
This file contains hidden or 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
| /// <summary> | |
| /// A base class that implements a singleton pattern. | |
| /// <example> | |
| /// Declaring a singleton class: | |
| /// <code> | |
| /// public class Singleton : SingletonBase<Singleton> | |
| /// { | |
| /// 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