Private Constructor in Depth
What is Private Constructor -
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
Why and Where we Use Private Constructor -
Private constructors are useful in cases where it is undesirable for a class to be created by code outside of the class. Singletons, factories, static method objects are examples of where being able to restrict construction of a type is useful to enforce a particular pattern.
Why Singleton Are needed if Static Class Exists -
singletons and static classes are not equivalent.
For example
(1) a singleton class can implement an interface, a static class cannot.
(2) A singleton object may be passed to methods as a parameter - this is not so easy to do with static classes without resorting to wrapper objects or reflection.
(3) There are also cases where you may want to create an inheritance hierarchy in which one (or more) of the leaf classes are singleton - this is not possible with static classes either. As another example
(4) You may have several different singletons and you may want to instantiate one of them at runtime based on environmental or configurational parameters - this is also not possible with static classes.
How Singleton Pattern related to Private constructor -
The singleton pattern allows only one instance of the class in an application. It does this by having a static private variable within the class of that class's type. A static method instanciates the variable if it is null (using the private constructor), and returns it.
The constructor is private to prevent more than one instance of the class being created.
Such a pattern is useful, for example, when creating a logging class where only one instance should occur to prevent IO conflicts with the log file.
sample Code -
namespace PrivateConstrutor
{
public class Base // if use SEALED keyword class can't inherit
{
// private Counter() { } // if uncomment this line class can't inherit
public Counter() { }
public static int Bottle;
public static int BottleCount()
{
return ++Bottle;
}
}
public class Drive: Base
{
string s = "Ajay Chourasia";
}
class TestCounter
{
static void Main()
{
Drive Dr= new Drive ();
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
//Base bs= new Counter(); // Error
Base.Count= 100;
Base.BottleCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
Console.ReadKey();
}
}
}
Summery - Use private if you were creating a singleton object as you don't want the constructor publicly available.