The source code to demonstrate the constructor overloading is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to demonstrate constructor overloading.
using System;
class CtorOver
{
public CtorOver(int a, int b)
{
int result = 0;
result = a + b;
Console.WriteLine("Sum is: " + result);
}
public CtorOver(int a, int b, int c)
{
int result = 0;
result = a + b + c;
Console.WriteLine("Sum is: " + result);
}
public CtorOver(int a, int b, int c, int d)
{
int result = 0;
result = a + b+c+d;
Console.WriteLine("Sum is: " + result);
}
static void Main(string[] args)
{
CtorOver C1 = new CtorOver(10, 20);
CtorOver C2 = new CtorOver(10, 20,30);
CtorOver C3 = new CtorOver(10, 20,30,40);
}
}
Output:
Sum is: 30
Sum is: 60
Sum is: 100
Press any key to continue . . .
Explanation:
In the above program, we created a class CtorOver, here, we overloaded the constructor based on the number of arguments to calculate the sum of given arguments.
public CtorOver(int a, int b)
public CtorOver(int a, int b, int c)
public CtorOver(int a, int b, int c, int d)
Now look to the Main() method. Here, we created the three objects C1, C2, and C3. Then called each overloaded constructor one by one and printed the result on the console screen.
Program:
The source code to demonstrate the constructor overloading is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class CtorOver, here, we overloaded the constructor based on the number of arguments to calculate the sum of given arguments.
Now look to the Main() method. Here, we created the three objects C1, C2, and C3. Then called each overloaded constructor one by one and printed the result on the console screen.