C sharp - Constructor Overloading in C#
What is Constructor Overloading?
Constructor overloading means creating multiple constructors in the same class with different parameter lists. It allows you to create objects in different ways.
Key Points
-
Constructors must have the same name (class name).
-
Each constructor must have a different number or type of parameters.
-
Helps in flexible object initialization.
Syntax
class ClassName
{
public ClassName() { }
public ClassName(type param1) { }
public ClassName(type param1, type param2) { }
}
Simple Example
using System;
class Person
{
public string name;
public int age;
// Default constructor
public Person()
{
name = "Unknown";
age = 0;
}
// Constructor with one parameter
public Person(string personName)
{
name = personName;
age = 0;
}
// Constructor with two parameters
public Person(string personName, int personAge)
{
name = personName;
age = personAge;
}
public void ShowInfo()
{
Console.WriteLine("Name: " + name + ", Age: " + age);
}
}
class Program
{
static void Main()
{
Person p1 = new Person();
Person p2 = new Person("Alice");
Person p3 = new Person("Bob", 25);
p1.ShowInfo();
p2.ShowInfo();
p3.ShowInfo();
}
}
Output:
Name: Unknown, Age: 0
Name: Alice, Age: 0
Name: Bob, Age: 25