Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with both private as well as public constructor in C# can be instantiated - Strange

Folks, I am just learning about constructors. I am wondering why MS is allowing both private as well as public constructor in a class. If I have both public and private constructor, it apparently fails the purpose of private constructor as in, it allows the creation of instance of the class outside. I find it strange. What I would expect is, if both private and public constructors are present in a class, it should be a compile time error.

Can someone please explain the usage with example and the reason.

like image 367
Jasmine Avatar asked Nov 19 '25 11:11

Jasmine


2 Answers

There's nothing wrong with having both public and private constructors. One example follows.

It could be that three different public constructors share a large portion of initialization logic. Rather than repeating the same logic three times, it would make sense to have a private constructor that performs the common parts, and then have the public constructors delegate to the private constructor for the common parts.

This isn't the only use case, but it should be enough to convince you I hope.

like image 175
Timothy Shields Avatar answered Nov 21 '25 02:11

Timothy Shields


At first it initialize with public constructor and the private has no use. Compiler only look for public constructor so that it can be initialize outside the class. private Constructor is treated as normal method or we can say another version of constructor, also there must be some difference in constructors signature.

like image 20
A.T. Avatar answered Nov 21 '25 02:11

A.T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!