Explaining Constructors in C#

Contents
  • Abstract
  • Introduction

    • Behind the scenes

  • Types of Constructor

    • Default Constructor
    • Parameterized Constructor

  • Access Modifiers and Prefix with Constructors

    • Using Access Modifier private with Constructor
    • Using prefix static with Constructor
    • Calling Parent Class Constructors in child class during inheritance

  • Points of interest
  • Conclusion
Abstract
 
In this article we will explain CSharp constructors.
 
Introduction
 
In a simple words Constructor is nothing but a method, a special kind of method of a class that gets executed when its (class) object is created.
Lets discuss it in details.
 
"A constructor is a class method automatically executed whenever class's object is created or whenever class is initialized."
 
Consider following bit of code:
  1. public class MsDotNetHeaven  
  2. {  
  3. public MsDotNetHeaven()  
  4. {  
  5. //A default Constructor  
  6. }  
  7.   
  8. //Class members  
  9.   
  10. }  
In the preceding snippet, try to change the name of constructor from MsDotNetHeaven to MsDotNetMentor and see what happened. Crap! you can't do that, you have to assign a same name as of class.
 
Behind the scenes
 
What happened behind the scenes with preceding code. Its nothing but whenever you try to create an object of a class or initialize a class, the default constructor is automatically invoked.
 
See following snippet: 
  1. //Initializes the Class  
  2. MsDotNetHeaven objMsDnH = new MsDotNetHeaven();  
Types of Constructor
 
Segregation of constructors in types always an issue for debate but I would like segregated Constructors in following types:
 
Default Constructor 
 
A constructor that takes no parameters is called a default constructor, also called as parameterless constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.
 
Parameterized Constructor
 
Besides a default constructor, when it required to pass some argument on the initialization of a class. A parameterized constructor comes into picture. It follows the same rules as default constructor but with slightly difference, it has some parameters so, it differs from default constructor.
 
Go through following snippet:
  1. public class MsDotNetHeaven  
  2. {  
  3. public MsDotNetHeaven()  
  4. {  
  5. //A default Constructor  
  6. }  
  7.   
  8. public MsDotNetHeaven(String strName)  
  9. {  
  10. //A parameterized Constructor having one parameter  
  11. }  
  12. public MsDotNetHeaven(String strFirstName, String strLastName)  
  13. {  
  14. //A parameterized Constructor having two parameters  
  15. }  
  16.   
  17. //Class members  
  18.   
  19. }  
Please note that:
  • A default constructor should be explicitly declared, while declaring parameterized constructor.
  • Some writer also take Private constructor and Static Constructor as types of constructor but in my view these are constructor with different modifiers so behave differ; I will cover these in next section.
Access Modifiers and Prefix with Constructors
 
By default Constructors are public but we can also use other modifiers and prefix like private and static. With the use of these modifiers constructors behave differently:
 
Using Access Modifier private with Constructor
 
A constructor with private access modifier is known as private constructor.
 
A private constructor is a special instance constructor. It is 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 that class.
 
Some time there is a need where we have not allow outer world to get instantiate our class then we need to use private modifier with constructor.
 
Consider following code snippet:
  1. public class MsDotNetHeaven  
  2. {  
  3. private MsDotNetHeaven()  
  4. {  
  5. //A default Constructor as private  
  6. }  
  7.   
  8. //Class members  
  9.   
  10. }  
Now whenever you try to invoke following piece of code,
  1. //Initializes the Class  
  2. MsDotNetHeaven objMsDnH = new MsDotNetHeaven();  
It throws an error: Constructors. MsDotNetHeaven. MsDotNetHeaven () is inaccessible due to its protection level.
 
Now, question comes to mind if the preceding contains error then what is the use is a private constructor, we can make the preceding class to be initialized by declaring another public constructor.
 
Lets modify preceding above code-snippet:
  1. public class MsDotNetHeaven  
  2. {  
  3.    private MsDotNetHeaven()  
  4.    {  
  5.       //A default Constructor as private  
  6.    }  
  7.    public MsDotNetHeaven(String strName): this()  
  8.    {  
  9.       //A parameterized Constructor having one parameter  
  10.       System.Console.WriteLine(“My name is : “ + strName);  
  11.    }  
  12.    //Class members  
  13. }  
Now, you can initialize class as follow:
  1. //Initializes the Class  
  2. MsDotNetHeaven objMsDnH = new MsDotNetHeaven(“Gaurav Kumar Arora”);  
Using prefix static with Constructor
 
With the use of static with constructor gives a name as static constructor
 
For C++ developers it's a new concept introduced in C#.
 
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
 
Consider the following snippet:
  1. public class MsDotNetHeaven  
  2. {  
  3.    static MsDotNetHeaven()  
  4.    {  
  5.       //A static Constructor  
  6.       // Can only access static members here.  
  7.   
  8.       System.Console.WriteLine("I am a static constructor.");  
  9.    }  
  10.    //Class members  
  11. }  
Now whenever you create an instance of the class MsDotNetHeaven the line I am a static constructor get printed.
 
Consider following snippet:
  1. public class MsDotNetHeaven  
  2. {  
  3.    static MsDotNetHeaven()  
  4.    {  
  5.       //A static Constructor  
  6.       // Can only access static members here.  
  7.   
  8.       System.Console.WriteLine("I am a static constructor.");  
  9.    }  
  10.   
  11.    public MsDotNetHeaven()  
  12.    {  
  13.    //A default Constructor  
  14.    }  
  15.   
  16.    //Class members  
  17.   
  18. }  
The preceding code is perfectly alright and will produce the same result as the preceding code.
 
Calling Parent Class Constructors in child class during inheritance
 
Now, consider a scenario of inheriting a class and want to use a parent class constructor. How to do that? Simple, it can be done using base().
 
Consider the following code snippet:
  1. public class MsDotNetHeaven   
  2. {  
  3.     public MsDotNetHeaven()   
  4.     {  
  5.         //A default Constructor    
  6.     }  
  7.   
  8.     public MsDotNetHeaven(String strName)   
  9.     {  
  10.         //A parameterized Constructor having one parameter    
  11.     }  
  12.     //Class members    
  13.   
  14. }  
  15.   
  16. public class MsDotNetMentor: MsDotNetHeaven   
  17. {  
  18.     public MsDotNetMentor()   
  19.     {  
  20.         //A default Constructor    
  21.     }  
  22.   
  23.     public MsDotNetMentor(String strName): base(strName)   
  24.     {  
  25.         //A parameterized Constructor having one parameter    
  26.     }  
  27.     //Class members    
  28.   
  29.     static void Main()   
  30.     {  
  31.         MsDotNetMentor objMsDnM = new MsDotNetMentor(); //(A)    
  32.         MsDotNetMentor objNameMsDnM = new MsDotNetMentor(“Gaurav Arora”); //(B)    
  33.     }  
  34. }  
(A) From the preceding: the sequence of invoking a constructor is first public MsDotNetHeaven() and then public MsDotNetMentor().
 
(B) From the preceding: the sequence of invoking a constructor is public MsDotNetHeaven(String strName) and then public MsDotNetMentor(String strName).
Please note that:
  • A static constructor should not be declared with any access modifier.
  • A static constructor does not accept parameters.
  • A static constructor is called automatically.
  • There is no way to call a static constructor directly.
  • Can't stop the execution of Static constructor.
Points of interest
  • Constructor is nothing but a special method that initializes the class or its task to initialize the object of its class.
  • Its name must be the same as the name of the class
  • This is a special method since constructors do not have return types, not even void
  • A constructor cannot return a value because they didn't have a return type.
  • A constructor can't be inherited, although a derived class can call the base class constructor.
  • A class has at least one constructor, also known as the default constructor (a constructor without a parameter)
  • You have to explicitly write a default constructor while Overloading constructors.
  • Multiple constructors of a class declared with a different set of parameters is known as constructor overloading.
  • A constructor can call another constructor using this().

Conclusion

In this article we discussed all the basics of constructors, their types and access modifiers.

Up Next
    Ebook Download
    View all
    Learn
    View all