Advantage of Private constructor in C#
what is the advantage of Private constructor in C# languages ?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ehsan SajjadRank #512 · 4.8K reputationPosted Jan 17, 2016, 10:15 AM EST
Jignesh TrivediRank #16 · 50.3K reputationPosted Jun 25, 2012, 3:05 AM EDT
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
A private constructorhelp us to prevent the runtime from adding an empty contructure automatically
Restricting access to object creation.
hope this will help you.
S G91 reputationPosted Jun 25, 2012, 3:39 AM EDT
Private constructor...
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
Actually this is use for private constructor which r used to prevent new creation of the instances of a class when there are no instance fields or methods.
Sandeep Mishra2 reputationPosted Jan 16, 2016, 9:27 AM EST
You can also create a constructor as private. When a class contains at least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static.
Nick Chamberlain114 reputationPosted Jan 16, 2016, 9:58 AM EST
MahaRank #2,573 · 543 reputationPosted Jan 16, 2016, 1:46 PM EST
VulpesRank #55 · 29.2K reputationPosted Jun 25, 2012, 2:12 AM EDT
1. You want to control instantiation i.e. to limit the number of instances that can be created - say, to one, when implementing the 'singleton' pattern.
2. You want to avoid throwing an exception in the instance constructor itself if invalid arguments are passed to it. Even if you catch the exception, the instance created may be left in an unstable state.
In both these cases you can define a public static 'factory' method (or property) of the same class which only calls the private constructor when needed or safe to do so.
You can also use a private constructor to prevent instantiation entirely but a better way to do this is to use a static class which can only contain static members and cannot therefore contain an instance constructor at all.