Tutorial by Examples

public class Singleton { private readonly static Singleton instance = new Singleton(); private Singleton() { } public static Singleton Instance => instance; } This implementation is thread-safe because in this case instance object is initialized in the static constructor. The ...
This thread-safe version of a singleton was necessary in the early versions of .NET where static initialization was not guaranteed to be thread-safe. In more modern versions of the framework a statically initialized singleton is usually preferred because it is very easy to make implementation mistak...
.Net 4.0 type Lazy guarantees thread-safe object initialization, so this type could be used to make Singletons. public class LazySingleton { private static readonly Lazy<LazySingleton> _instance = new Lazy<LazySingleton>(() => new LazySingleton()); public stati...
Because in .NET 3.5 and older you don't have Lazy<T> class you use the following pattern: public class Singleton { private Singleton() // prevents public instantiation { } public static Singleton Instance { get { return Nested.instanc...
Most examples show instantiating and holding a LazySingleton object until the owning application has terminated, even if that object is no longer needed by the application. A solution to this is to implement IDisposable and set the object instance to null as follows: public class LazySingleton : ID...

Page 1 of 1