Basically, it is a method in the class which executed when its object is created. We put the initialization code in the constructor. Creating a constructor in the class is pretty simple.
Look at the following sample:
- public class mySampleClass
- {
- public mySampleClass()
- {
-
- }
-
- }
When the object of this class is instantiated this constructor will be executed automatically.
Like this:
-
- mySampleClass obj = new mySampleClass()
Constructor Overloading: C# supports overloading of constructors, that means we can have constructors with different set of parameters. So our class can be like the following code snippet:
- public class mySampleClass
- {
- public mySampleClass()
- {
-
- }
- public mySampleClass(int Age)
- {
-
- }
-
- public mySampleClass(int Age, string Name)
- {
-
- }
-
-
- }
Well, note here that call to the constructor now depends on the way you instantiate the object.
For example: - mySampleClass obj = new mySampleClass()
-
-
- mySampleClass obj = new mySampleClass(12)
-
The call to the constructors is completely governed by the rules of the overloading here.
Calling Constructor from another Constructor: You can always make the call to one constructor from within the other.
Say for example: - public class mySampleClass
- {
- public mySampleClass(): this(10)
- {
-
- }
-
- public mySampleClass(int Age)
- {
-
- }
- }
First of all let us see what is this syntax:
Here this refers to the same class, so when we say this(10), we actually mean execute the public SampleClass (int Age) method. The above way of calling the method is called initializer. We can have at the most one initialize in this way in the method.
Another thing which we must know is the execution sequence i.e., which method will be executed when. Here if I instantiate the object as:
- mySampleClass obj = new mySampleClass()
Then the code of
public mySampleClass(int Age) will be executed before the code of mySampleClass(). So practically the definition of the method:
- public mySampleClass(): this(10)
- {
-
- }
is equivalent to:
- public mySampleClass()
- {
- mySampleClass(10)
-
- }
This is sometimes called Constructor chaining.