A private constructor is a special instance constructor. It is typically used in classes that contain only static members. if a class has one or more private constructors and no public constructors, other classes (other than nested classes) cannot create instances of the class. For example:
C#
Class nlog{ //private Constructor: private NLog () {} public static double e = MATH.E; 2.71828 ...}
declaring an empty constructor prevents the default constructor from being automatically generated. Note that if you do not use the access modifier for the constructor, it is still private by default. private modifier is usually used explicitly to make it clear that the class cannot be Instan tiated. " However, it is usually explicitly used with the private modifier to clearly indicate that the class cannot be instantiated.
math class, or when a method was called to obtain an instance of a class." When there are no instance fields or instance methods, such as the Math class, or when a method is called to obtain an instance of the class, the private constructor can be used to block the creation of an instance of the class. If all the methods in the class are static, consider making the entire class static. static class and Static Class members (C # Programming Guide). " > For more information, see Static classes and Static Class members (C # Programming Guide).
The following is an example of a class that uses a private constructor.
C#
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'll generate // An error because the constructor is inaccessible: //Counter acounter = new Counter (); Error counter.currentcount = +; Counter.incrementcount (); Console.WriteLine ("New count: {0}", Counter.currentcount); Keep the console window open in debug mode. Console.WriteLine ("Press any key to exit."); Console.readkey (); }} Output:new count:101
Note that if you uncomment the following statement in the example, it generates an error because the constructor is inaccessible because of its protection level:
C#
Counter acounter = new Counter (); Error
Private constructors (C # Programming Guide)