In this article i will explain what is private constructor and what is the use of private constructor.
When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only.
Some key points of a private constructor are:
- It provide an implementation of a singleton class pattern.
- One use of private constructor is when we have only static members of class.
- If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
using System;
public class Program
{
public static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount=100;
Console.WriteLine("Counter before increment {0}",Counter.currentCount);
Counter.IncrementCount();
Console.WriteLine("Counter after increment {0}",Counter.currentCount);
}
}
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
Output :
Counter before increment 100
Counter after increment 101
When we use private constructor:
- Use private constructor when class have only static members.
- Prevents the creation of instance of that class.
- If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor
No comments:
Post a Comment