public sealed class EventBus { private static readonly EventBus instance = new EventBus(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static EventBus() { } private EventBus() { } public static EventBus Instance { get { return instance; } } }
Using .NET 4’s Lazy<T> type
public sealed class Singleton5 { private Singleton5() { } private static readonly Lazy<Singleton5> lazy = new Lazy<Singleton5>(() => new Singleton5()); public static Singleton5 Instance { get { return lazy.Value; } } }
References
https://csharpindepth.com/articles/singleton
https://www.c-sharpcorner.com/UploadFile/8911c4/singleton-design-pattern-in-C-Sharp/
https://riptutorial.com/csharp/example/6795/lazy–thread-safe-singleton–using-lazy-t–