Constructor overloading in C# means writing more than one constructor in the same class, but with different parameters. It lets you create objects in different ways, depending on what information you have when making the object.
- You can overload a constructor by changing the number of parameters or their types.
- Each constructor must look different so the compiler knows which one to call.
- This makes object creation more flexible and easier to use.
We can achieve Constructor overloading in many different ways.
1. Overloading by Changing Number of Parameters
A class may have constructors that accept different numbers of parameters. This allows objects to be initialized with varying levels of detail.
using System;
class Student {
string name;
int age;
// Constructor 1: No parameter
public Student() {
name = "Unknown";
age = 0;
}
// Constructor 2: One parameter
public Student(string name) {
this.name = name;
age = 18;
}
// Constructor 3: Two parameters
public Student(string name, int age) {
this.name = name;
this.age = age;
}
public void Display() {
Console.WriteLine("Name: " + name + ", Age: " + age);
}
public static void Main() {
Student s1 = new Student();
Student s2 = new Student("John");
Student s3 = new Student("Alice", 22);
s1.Display();
s2.Display();
s3.Display();
}
}
Output
Name: Unknown, Age: 0 Name: John, Age: 18 Name: Alice, Age: 22
2. Overloading by Changing Data Types
Constructors can also differ by the type of parameters. For example, one constructor may accept integers while another accepts doubles.
using System;
class Calculator {
int result;
// Constructor with int
public Calculator(int x, int y) {
result = x + y;
}
// Constructor with double
public Calculator(double x, double y) {
result = (int)(x + y);
}
public void ShowResult() {
Console.WriteLine("Result: " + result);
}
public static void Main() {
Calculator c1 = new Calculator(10, 20);
Calculator c2 = new Calculator(5.5, 4.5);
c1.ShowResult();
c2.ShowResult();
}
}
Output
Result: 30 Result: 10
3. Overloading by Changing Order of Parameters
Even if the types are the same, changing the order of parameters makes constructors distinct.
using System;
class Employee {
string name;
int id;
// Order: string, int
public Employee(string name, int id) {
this.name = name;
this.id = id;
}
// Order: int, string
public Employee(int id, string name) {
this.name = name;
this.id = id;
}
public void Display() {
Console.WriteLine("Name: " + name + ", Id: " + id);
}
public static void Main() {
Employee e1 = new Employee("Alice", 101);
Employee e2 = new Employee(102, "Bob");
e1.Display();
e2.Display();
}
}
Output
Name: Alice, Id: 101 Name: Bob, Id: 102
Note
- A static constructor cannot be overloaded because it always has no parameters.
- A private constructor can be overloaded, but it can only be used inside the same class since private members are not accessible from outside the class.