Private Constructor

A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. For example:
class NLog
   // Private Constructor:
   private NLog() {}

   public static double e = 2.71828;
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don’t use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private constructors are useful to prevent creation of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
The following is an example of a class using a private constructor.
// PrivateCtor1.cs
using System;

public class MyClass
   private MyClass() {}
   public static int counter;
   public static int IncrementCounter()
      return ++counter;

class MainClass
   static void Main()
      // If you uncomment the following statement, it will generate
      // an error because the constructor is inaccessible:
      // MyClass myObject = new MyClass();   // Error
      MyClass.counter = 100;
      Console.WriteLine("New count: {0}", MyClass.counter);
New count: 101
Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible due to its protection level:
// MyClass myObject = new MyClass();   // error


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s