Thursday, 28 November 2013

What is the use of a 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.

Private constructors are used

When you have a class that should only be created through factory methods. 

When you have overloads of the constructor, and some of them should only be used by the other constructors. 

When you want to prevent the users of your class from instantiating the class directly, Singletons for example

When you want to use it from a static factory method inside the same class

When you want to prevent the runtime from adding an empty constructor automatically.
  public class Complex
        public double real;
        public double imaginary;
        public static Complex FromCartesianFactory(double real, double imaginary)
            return new Complex(real, imaginary);
        public static Complex FromPolarFactory(double modulus, double angle)
            return new Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle));
        private Complex(double real, double imaginary)
            this.real = real;
            this.imaginary = imaginary;
Complex product = Complex.FromPolarFactory(1, Math.PI);
What is the need of private constructor in C#?

No comments:

Post a Comment