.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Forum >> OOPS >> Post New QuestionBookmark and Share Subscribe to Forum

Use of Private Constructors

Posted By: Deco     Posted Date: September 21, 2010    Points:2   Category :OOPS
Can any one please tell me where we will use Private constructors?

Responses
Author: Jean Paul             
Posted Date: September 27, 2010     Points: 5   

Alwyn Dude,

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'

Code Example:
public class LogUtil
{
private LogUtil()
{
}

private static LogUtil _instance;

public static LogUtil GetInstance()
{
if (_instance == null)
_instance = new LogUtil();

return _instance;
}

public void Write(string message)
{
// Write to file
}
}

Usage: LogUtil.GetInstance().Write("test message..");

Regards.


Jean Paul http://jeanpaulva.com/


Post Reply

You must Sign In To post reply
 
 
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery
JavaScript/VBScriptBiztalkWPFPatten/PracticesWCFOthers
www.DotNetSpark.comUnAnsweredAll

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend