Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Last active December 28, 2023 03:34
Show Gist options
  • Save HamidMolareza/08d9aa9dd3469c3961a2e29f85ab2d8f to your computer and use it in GitHub Desktop.
Save HamidMolareza/08d9aa9dd3469c3961a2e29f85ab2d8f to your computer and use it in GitHub Desktop.
The best way to define a Thread-Safe singleton class in C#
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