How I Can Call Multiple Constructors By Making A Single Object

Today, I am going to show you how we can call multiple constructors by making a single object in Main class.

INTRODUCTION

Today, I am going to show you how we can call multiple constructors by making a single object in the Main class.

Explanation

My motive to write this code is that I want to show you that how we can call multiple constructors by a single object.

Step 1

In all statements, start with using namespaces, as that is required to implement our code. 

Step 2

Then, I used class A, and a public modifier for it,
  • First, I will pass default constructor for class A that will automatically be called while our object is created.
  • Then I will make another constructor having some parameters, [you may pass any parameter]
  • In the second, third, and fourth constructor I will pass int parameters. 
  • In the second one, I will pass two parameters, because we cannot pass the same parameter or the same datatype parameter without using overriding.
  • In this program, I will use ''OVERLOADING"
OVERLOADING: HAVING THE SAME NAME BUT DIFFERENT PARAMETERS.

Step 4

I will use new class B, which only has a single constructor.

Step 5

At last, in the main class, I will create an object of class B.

Step 6

You must be thinking that's why I used this keyword with all constructors.

Step 7

Through this keyword we can call a constructor. 

Step 8

Use Breakpoint on every constructor, so that you will find how the code is working.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace Interfaces {  
  6.     public class a {  
  7.         public a(): this(2, 2) {  
  8.             Console.WriteLine("call 2 parameter method");  
  9.         }  
  10.         public a(int a, int b): this(2, 2, 2, 2, 2) {  
  11.             Console.WriteLine("call 4 parameter method");  
  12.         }  
  13.         public a(int a, int b, int c, int d): this(2, 2) {  
  14.             Console.WriteLine("call 5 parameter method");  
  15.         }  
  16.         public a(int a, int b, int c, int d, int e) {  
  17.             Console.WriteLine("4 parameter");  
  18.         }  
  19.         public a(string ABC): this() {  
  20.             Console.WriteLine("string parameter");  
  21.         }  
  22.     }  
  23.     public class b: a {  
  24.         public b() {  
  25.             Console.WriteLine("b parametre");  
  26.         }  
  27.     }  
  28.     class main {  
  29.         public static void Main() {  
  30.             b obj = new b();  
  31.         }  
  32.     }  
  33. }