Home »
.Net »
C# Programs
C# - Implement Constructor Overloading
Here, we are going to learn how to implement constructor overloading using C# program?
Submitted by Nidhi, on November 09, 2020 [Last updated : March 22, 2023]
Constructor Overloading
In the Constructor overloading, we can create multiple constructor methods with the same name based on:
- Number of arguments
- Type of arguments
- Order of arguments
Here, we will overload the constructor of CtorOver class and calculate the sum of given arguments.
C# program to implement constructor overloading
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.
C# Basic Programs »