Private Constructors in C#

Recently I had a discussion with the technical team to use Constructors  in our project and I had a  doubt that what does a private constructor do ? What purpose does they solve.So I googled and here I am summarizing the facts.

Firstly, a private Constructor is used when you don’t want to create an object for the class.These are 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.

Secondly,We cannot inherit from classes that are having only private constructors. The reason is suppose if you are inheriting from a base class which has only private constructors and if you create an object for the derived class then the base class constructor will be called. Because the base class contains only private constructors and  due to ‘private’ access modifier  it is not accessible from the derived  class. So it will give you an error with a syntax as follows ‘Error 1 ‘ConsoleApplication2.Program.Program()’ is inaccessible due to its protection level’

Where do you find Private constructors are useful? 

Private constructors can also be useful for:
  classes containing only static utility methods
  classes containing only constants
  type safe enumerations 

A class can contain both private and public constructor and objects of such classes can also be created, but not by using the private constructor.

This entry was posted in .NET Framework. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s