A private constructor is a special instance constructor used in class that contain static member only. If a class have one or more private constructor and no public constructor then other classes (except nested classes ) are not allowed to create instance of this class. Means, we can neither create the object of the class nor it can be inherit by other class.
The public constructor can access the private constructors from within class through constructor chaining.
- using System;
- public Class demo {
- private demo()
- {
- Console.WriteLine("This is no parameter private constructor");
- }
- public demo(int a):this()
- {
- Console.WriteLine("This is one parameter public constructor");
- }
- // other methods
- }
The object of the class can be created as :
- demo obj = new demo(10) ; //it will work fine.
But defining object like this won't work.
- demo obj = new demo() ; // error of inaccessibility will be occur.
Key points about private constructor
- one use of private construct is when we have only static member.
- It provide implementation of singleton class pattern
- Once we provide constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.
- If we still want to make object of the class having private constructor. We can have a set of public constructor along with the private constructor.
No comments:
Post a Comment