Win Surprise Gifts!!!
Top 5 Contributors of the Month
Post New Question
Subscribe to Forum
Use of Private Constructors
September 21, 2010
Can any one please tell me where we will use Private constructors?
Posted Date: September 27, 2010 Points: 5
Private constructors are used where we need to control the instantiation of the class.
Example: You have a LogUtil class - you wanted to assure that no body creates the instance outside and only one instance of the class is maintained throughout the windows application. As the LogUtil is dealing with a file named 'info.log' we need to make sure no file sharing issues should happen - thus we decided to make maximum number of instances of LogUtil class to 1.
So you can make the constructor as private. Eventhough it is private the class still can access it - as a class can access it's own private, internal, public and protected methods.
So now the question arises if instance cannot be created how outside world make use of the class. For the solution you have to provide static methods in the class that calls the private constructor internally. This will fall to the famous and simple design pattern 'Singleton'
public class LogUtil
private static LogUtil _instance;
public static LogUtil GetInstance()
if (_instance == null)
_instance = new LogUtil();
public void Write(string message)
// Write to file
Usage: LogUtil.GetInstance().Write("test message..");
To post reply
Related Questions Related Questions
What is the use of private constructor in c#?
difference between shared and private assembly?
Constructors in .net?
Latest Forum Questions From The Same Category
Brief explanation with sample examples on oops conects and Access Specifiers in .net?
propeties in c#
Real time example of Multiple Inheritance in C#
Encapsulation Vs Abstraction
Example for encapsulation
Real time example of multiple inheritance
What is function overriding? give me an example
SingleTon Design Patterns
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more
Quick Links For Forum Categories:
Hall of Fame
Terms of Service
Tell A Friend