What is the use of private constructor?

Posted by Shreedar under .NET Framework on 9/27/2015 | Points: 10 | Views : 373 | Status : [Member] | Replies : 4
In one of my interview, I was asked about constructors.
I answered like constructor is a special type of method which is called when an object is created for a class.
Then she asked why we use private constructor?

Regards

Sridhar Thota.
www.dotnet-sridhar.blogspot.com



Responses

Posted by: Rajnilari2015 on: 9/27/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
2
Down
Private Constructor is a special instance constructor used in class that contains static memory only.
The primary use of a private constructor is not to allow to create class instance when there are no instance fields or methods, or when a method is called to obtain an instance of a class. Some probable use cases are
a) The constructor can only be accessed from static factory method inside the class itself 

e.g Singleton Class (where not more than one instance of the class exists in the program.)


b) Limit the number of object of a class

c) Preventing creating copy of the class (i.e. copy constructor)

d) A utility class that only contains static methods. (though here we can use a static class but it's an option)

e) Class cannot be inherited

Hope this will be helpful

--
Thanks & Regards,
RNA Team

Shreedar, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 9/27/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
For more information , you can read

a) http://www.dotnetperls.com/private-constructor
b) http://stackoverflow.com/questions/2585836/why-do-we-need-a-private-constructor
c) http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html


--
Thanks & Regards,
RNA Team

Shreedar, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shreedar on: 9/27/2015 [Member] Starter | Points: 25

Up
0
Down
Hi

Thanks for reply. I got little answer from your response.

Regards

Sridhar Thota.
www.dotnet-sridhar.blogspot.com

Shreedar, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 9/27/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
I got little answer from your response.
OK.So what's the next expectation? How can I help you more ..please let me know.

--
Thanks & Regards,
RNA Team

Shreedar, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response