Contents
- Abstract
- Introduction
- 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:
- public class MsDotNetHeaven
- {
- public MsDotNetHeaven()
- {
-
- }
-
-
-
- }
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:
-
- 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:
- public class MsDotNetHeaven
- {
- public MsDotNetHeaven()
- {
-
- }
-
- public MsDotNetHeaven(String strName)
- {
-
- }
- public MsDotNetHeaven(String strFirstName, String strLastName)
- {
-
- }
-
-
-
- }
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:
- public class MsDotNetHeaven
- {
- private MsDotNetHeaven()
- {
-
- }
-
-
-
- }
Now whenever you try to invoke following piece of code,
-
- 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:
- public class MsDotNetHeaven
- {
- private MsDotNetHeaven()
- {
-
- }
- public MsDotNetHeaven(String strName): this()
- {
-
- System.Console.WriteLine(“My name is : “ + strName);
- }
-
- }
Now, you can initialize class as follow:
-
- 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:
- public class MsDotNetHeaven
- {
- static MsDotNetHeaven()
- {
-
-
-
- System.Console.WriteLine("I am a static constructor.");
- }
-
- }
Now whenever you create an instance of the class MsDotNetHeaven the line I am a static constructor get printed.
Consider following snippet:
- public class MsDotNetHeaven
- {
- static MsDotNetHeaven()
- {
-
-
-
- System.Console.WriteLine("I am a static constructor.");
- }
-
- public MsDotNetHeaven()
- {
-
- }
-
-
-
- }
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:
- public class MsDotNetHeaven
- {
- public MsDotNetHeaven()
- {
-
- }
-
- public MsDotNetHeaven(String strName)
- {
-
- }
-
-
- }
-
- public class MsDotNetMentor: MsDotNetHeaven
- {
- public MsDotNetMentor()
- {
-
- }
-
- public MsDotNetMentor(String strName): base(strName)
- {
-
- }
-
-
- static void Main()
- {
- MsDotNetMentor objMsDnM = new MsDotNetMentor();
- MsDotNetMentor objNameMsDnM = new MsDotNetMentor(“Gaurav Arora”);
- }
- }
(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.