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:
public class Customer
{
private Customer()
{
}
public static string getCustomerName()
{
return "Hello World";
}
}
Access this getCustomerName() Function
class AccessCustomer
{
static void Main()
{
string a;
a = Customer.getCustomerName();
System.Console.WriteLine("Customer Private Constructor: {0}",a);
}
}
OUTPUT
Hello World
- you can not inherit the class or you can not create a object of class which has private constructor.
- which condition use private constructor
- Many time we do not want to create instance of certain classes like utility, common routine of classes.
Hope you liked my article. Please stay with me I will share more article with you.
Cheer