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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Interfaces {
- public class a {
- public a(): this(2, 2) {
- Console.WriteLine("call 2 parameter method");
- }
- public a(int a, int b): this(2, 2, 2, 2, 2) {
- Console.WriteLine("call 4 parameter method");
- }
- public a(int a, int b, int c, int d): this(2, 2) {
- Console.WriteLine("call 5 parameter method");
- }
- public a(int a, int b, int c, int d, int e) {
- Console.WriteLine("4 parameter");
- }
- public a(string ABC): this() {
- Console.WriteLine("string parameter");
- }
- }
- public class b: a {
- public b() {
- Console.WriteLine("b parametre");
- }
- }
- class main {
- public static void Main() {
- b obj = new b();
- }
- }
- }