Use of Private constructor in c#

Posted by Rahulchd3112 under C# on 8/1/2010 | Views : 5208 | Status : [Member] | Replies : 2
when static constructor is availabe then what is the need of private constructor?
and
how we can access the member of a class having only private constructor?

http://howinaspnet.blogspot.com


Responses

Posted by: Poster on: 8/1/2010 [Member] Starter

Up
0
Down
Private constructor is generally used in the scenario where you do not want your user to create the instance of the class. The ideal example would be when you design a class based on Singleton pattern.

Read this article on your topic, that should help you understand the use of private constructor and how to access them from within the class

http://www.dotnetfunda.com/articles/article69.aspx
http://www.dotnetfunda.com/interview/exclusive/x1088-can-you-explain-singleton-pattern-.aspx
http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp-.aspx

Thanks

Rahulchd3112, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Muhilan on: 8/1/2010 [Member] Starter

Up
0
Down
Private constructor is a special instance constructor. Normally used in classes that contain only static members .
If particular has only constructors and no public contructors then nested classes are not allow to create instance of that class

ex..

public class Class1
{
private Sample() { }
public static int currentCount;
}

class Class2
{
void Main()
{
class1.currentCount;
}
}


Here no need to create instance of that class directly we can use class variable that time local variable to be initiazised using private constructor

Rahulchd3112, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response