What is the use of private constructor in a class
what is the use of private constructor in a class
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Sep 26, 2007, 10:46 AM
A private constructor prevents a class from being publicly instantiated.
In C# 1.0/1.1, you might want to do this if your class consists of nothing else but static members. However, following the introduction of 'static classes', this is no longer necessary in C# 2.0.
It has never been necessary in VB.Net which has the 'Module' to perform a similar function to the static class.
You might also want to use a private constructor if you only want to allow one object of a class to be instantiated (the so called 'singleton' pattern). You can then allow the single object to be created or accessed via a public static method or property of the class. The first time it is called, this method/ property would create the singleton by calling the private constructor internally.