Last active
December 28, 2023 03:34
-
-
Save HamidMolareza/08d9aa9dd3469c3961a2e29f85ab2d8f to your computer and use it in GitHub Desktop.
The best way to define a Thread-Safe singleton class 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
public sealed class MySingleton | |
{ | |
private static readonly Lazy<MySingleton> instance = new Lazy<MySingleton>(() => new MySingleton()); | |
private MySingleton() | |
{ | |
// Private constructor to prevent instantiation. | |
} | |
public static MySingleton Instance => instance.Value; | |
// Other members and methods of the singleton class can be added here. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment