|
The private constructor is a special instance constructor. It is usually used in a class that contains only static members. If a class has one or more private constructors and no public constructor, no other class (except nested classes) is allowed to create instances of that class. E.g:
class NLog
{
// Private Constructor:
private NLog() {} public static double e = System.Math.E; //2.71828...
}
Declaring an empty constructor prevents automatic generation of the default constructor. Note that if you do not use an access modifier on the constructor, it is still a private constructor by default. However, the private modifier is usually explicitly used to clearly indicate that the class cannot be instantiated.
When there is no instance field or instance method (such as the Math class) or when a method is called to obtain an instance of the class, a private constructor can be used to prevent the creation of an instance of the class. If all methods in the class are static, consider making the entire class static. For more information, see Static Classes and Static Class Members.
Examples
The following is an example of a class that uses a private constructor.
public class Counter
{
private Counter() {}
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}
Output
New count: 101
Note that if you uncomment the following statement in this example, it will generate an error because the constructor is not accessible due to its protection level:
// Counter aCounter = new Counter(); // Error |
|