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.
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.
Ehsan SajjadPosted Jan 17, 2016, 3:15 PM
MahaPosted Jan 16, 2016, 6:46 PM
Nick ChamberlainPosted Jan 16, 2016, 2:58 PM
Sandeep MishraPosted Jan 16, 2016, 2:27 PM
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.
S GPosted Jun 25, 2012, 7:39 AM
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.
Jignesh TrivediPosted Jun 25, 2012, 7:05 AM
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.
VulpesPosted Jun 25, 2012, 6:12 AM
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.