Factory
Private constructors can be useful when using the factory pattern (in other words, the static function used to get an instance of a class, not an explicit instance).
public class MyClass { private static Dictionary<object, MyClass> cache = new Dictionary<object, MyClass>(); private MyClass() { } public static MyClass GetInstance(object data) { MyClass output; if(!cache.TryGetValue(data, out output)) cache.Add(data, output = new MyClass()); return output; } }
Pseudo-sealed with nested children
Any nested classes that inherit from an outer class can call a private constructor.
For example, you can use this to create an abstract class that you can inherit, but no one else (the internal constructor would also work here to limit inheritance to one assembly, but the constructor of the private constructor should all implementations be nested classes.)
public abstract class BaseClass { private BaseClass() { } public class SubClass1 : BaseClass { public SubClass1() : base() { } } public class SubClass2 : BaseClass { public SubClass2() : base() { } } }
Base constructor
They can also be used to create โbasicโ constructors called from different, more accessible constructors.
public class MyClass { private MyClass(object data1, string data2) { } public MyClass(object data1) : this(data1, null) { } public MyClass(string data2) : this(null, data2) { } public MyClass() : this(null, null) { } }
Adam Robinson Apr 6 2018-10-06T00: 00Z
source share