Been reading MSDN, they mention that private constructors might be needed if a class has only static members etc, like the Math class. But the Math class is actually a static class. Also they mention "or when a method is used to obtain an instance of class" - I can imagine how it works but can you give me an example?
Asked
Active
Viewed 112 times
0
-
Here is one part - http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp – Jafar Kofahi Aug 13 '13 at 13:10
-
and here is the second http://stackoverflow.com/questions/8389043/why-have-a-private-constructor – Jafar Kofahi Aug 13 '13 at 13:11
-
Following the first link in a Google search - ["Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor."](http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.90).aspx) – Bernhard Barker Aug 13 '13 at 13:12
3 Answers
1
The second point is what the Singleton Pattern depends on. Basically, a class can manage how it is instantiated by making its constructor private. When it does, consumers cannot do this:
var obj = new MyClass();
...because the constructor is private. This means, the only way a consumer can get an instance of this class.. is via a method or property. Such as:
public MyClass GetInstance() {
return new MyClass();
}
(note: not a Singleton, just an example method)

Simon Whitehead
- 63,300
- 9
- 114
- 138
0
You use a private or protected constructors if the client of an API etc. should not directly be able to instantiate a class(type). Another common usecase is the Singleton pattern, like Simon as already mentioned:
public class MySingleton
{
private static MySingleton _instance;
private MySingleton() {} // private constructor
public static MySingleton Instance
{
get
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
}

Marco
- 2,189
- 5
- 25
- 44
0
"..when method is used to obtain an instance of class..." is a Gang of Four factory method design pattern:

Dmitry Bychenko
- 180,369
- 20
- 160
- 215
-
Your phrasing is a bit off, leading to... No it isn't. The factory method pattern may be an example of what was mentioned in the quote, but it's not the same thing (i.e. Singleton is another example). – Bernhard Barker Aug 13 '13 at 13:39