Monday, 26 August 2013

Private Constructor in c#

What is a private Constructor?
At the very out set a private constructor is a constructor with an access specifier "private".

Class Employee                  
{
     private Employee()
     {
     }
}

As simple as it is.
 Now there are two important characteristics of a private constructor or we can say a class with a private constructor.

A class with a private constructor

1>Can not be inherited:
Eg: in context of the above example if we try something like:
Class Programmer : Employee
{

}
 The above code throw compile time exception.

2>Can not be instantiated:
Eg: Employee obj = new Employee() is not possible.

Why then we use private constructor?
There are many utility classes we use in our project. Utility classes contain functions that can be used across different files. In such scenarios we are not always interested in creating the object and using those classes. If we have a class with private constructor and the utility methods are static in nature than we can call those method with out instantiating a class. As instantiating class would require memory allocation for all members we are saved for those un-necessary memory foot prints.

public class Employee
{
       private Employee()
      {
      }
      public static void AddNewEmployee(){//...write your code here}
}

Main()
{
    //--Here we can call the "AddNewEmployee() method with out instantiating the object
   Employee.AddNewEmployee();
}



I hope this was easy to understand. In the next article I will try to explain why would we need a private constructor if there is a static class available.

Comments and suggestions are always welcome.

No comments:

Post a Comment