Click here to Skip to main content
15,898,036 members

Response to: Question on Private Constructor

Revision 1
Private constructor is used to disable construction of a class using a constructor. It makes sense for a non-static class, of course. Let's set aside static constructors: they do not allow access modifiers at all, and are always treated as private.

Here is why: if no constructors defined, one default implicitly defined constructor still allows to instantiate this class. Naturally, this constructor is parameterless. So, defining a private parameterless constructor makes it impossible to construct an instance of a class. Other private constructors can be also added.

Now, why? Apparently, if an object cannot be constructed outside of the class, it can be constructed inside. So the purpose of all this activity is actually to create a factory method which returns the instantiated instance of the same class. Apparently, even though all constructors are private, inside class construction can be performed.

Why not a usual way, with non-private constructors? By different reasons an author of code designer may think of, but one of the is essential: because such factory method might return instances of some derived classes. So, compile-time return type is of the same class (which therefore can also be abstract), but run-time types returned are derived (and, of course, never abstract).

For a good example, look at this FCL type: . It has no constructors at all, but it has a factory method Create. How it works? It does not have public or internal constructor (sorry, not a perfect example: the constructors are not private, but it's still interesting to get an idea). Instead, you use factory methods. It's most interesting to consider the factory method Create(string). It is supposed to be a URI string, and the actual run-time type is determined by the URI scheme (http://en.wikipedia.org/wiki/URI_scheme[^]). Depending of the scheme detected, one of the derived types is constructed and returned: HttpWebRequest, HttpFtpRequest, etc.

Please see:
http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx[^].

—SA
Posted 25-Jan-13 18:08pm by Sergey Alexandrovich Kryukov.
Tags: ,