Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of private constructor in C#?

Tags:

c#

What is the need of private constructor in C#? I got it as a question for a C# test.

like image 839
softwarematter Avatar asked May 28 '09 09:05

softwarematter


People also ask

What is the purpose of a private constructor Javatpoint?

The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern. The use-cases of the private constructor are as follows: It can be used with static members-only classes.

What is the use of private constructor in abstract class?

A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as @Marko Topolnik answered).

What is the use of private constructor in Singleton class C#?

A singleton class has normal methods and you can call it using an instance. To prevent multiple instances of the class, the private constructor is used.

How does a private constructor work?

Private constructors allow us to restrict the instantiation of a class. Simply put, they prevent the creation of class instances in any place other than the class itself. Public and private constructors, used together, allow control over how we wish to instantiate our classes – this is known as constructor delegation.


1 Answers

For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)

like image 64
Svish Avatar answered Sep 27 '22 03:09

Svish