ReSharper 2016.3 Help

Code Inspection: Empty constructor

Having an empty constructor (whether static or not) in a class is redundant, and ReSharper issues a warning to that effect.

However, a special case warrants the use of the empty static constructor. When attempting to implement the Singleton pattern in .NET versions prior to 4.0 (i.e., prior to the appearance of a Lazy<T> type), the following construct is sometimes used:

class Singleton { static readonly Singleton instance = new Singleton(); private Singleton() {} public static Singleton Instance { get { return instance; } } static Singleton() { // this constructor is necessary } }

In the above, an empty static constructor is, in fact, a necessary detail that guarantees lazy initialization. An empty static constructor prevents the type from being marked with the beforefieldinit flag. When the type is not marked as beforefieldinit, the type's initializer method is executed by either the first access to a static or instance field or the first invocation of any instance, virtual or static method. Consequently, in the above example the empty singleton ensures that the type is only initialized when it is first accessed.

Developers wishing to utilize this behavior should disable this particular warning. Please note that in .NET 4.0, there is a simpler and safer way of implementing the Singleton pattern:

public class MyClass { private static readonly Lazy<MyClass> instance = new Lazy<MyClass>(() => new MyClass()); private MyClass(){} public static MyClass Instance { get { return instance.Value; } } }

See Also

Last modified: 15 February 2017