Constructor overloading lets you create objects in different ways by using multiple constructors with different inputs.
0
0
Constructor overloading in C Sharp (C#)
Introduction
When you want to create an object with different sets of starting information.
When some details are optional and you want to provide defaults if they are missing.
When you want to make your class easier to use by giving flexible ways to create objects.
Syntax
C Sharp (C#)
class ClassName { public ClassName() { /* code for no input */ } public ClassName(type1 param1) { /* code using param1 */ } public ClassName(type1 param1, type2 param2) { /* code using param1 and param2 */ } }
Each constructor has the same name as the class.
Constructors differ by the number or types of parameters.
Examples
This class has three constructors: one with no inputs, one with color only, and one with color and year.
C Sharp (C#)
class Car { public string color; public int year; public Car() { color = "unknown"; year = 0; } public Car(string c) { color = c; year = 0; } public Car(string c, int y) { color = c; year = y; } }
Shows how to create Car objects using different constructors.
C Sharp (C#)
Car car1 = new Car(); Car car2 = new Car("red"); Car car3 = new Car("blue", 2020);
Sample Program
This program creates three Car objects using different constructors and prints their color and year.
C Sharp (C#)
using System; class Car { public string color; public int year; public Car() { color = "unknown"; year = 0; } public Car(string c) { color = c; year = 0; } public Car(string c, int y) { color = c; year = y; } } class Program { static void Main() { Car car1 = new Car(); Car car2 = new Car("red"); Car car3 = new Car("blue", 2020); Console.WriteLine($"Car1: color={car1.color}, year={car1.year}"); Console.WriteLine($"Car2: color={car2.color}, year={car2.year}"); Console.WriteLine($"Car3: color={car3.color}, year={car3.year}"); } }
OutputSuccess
Important Notes
Constructor overloading helps make your code flexible and easier to use.
If you define any constructor, the default parameterless constructor is not created automatically.
Use different parameter types or counts to avoid confusion between constructors.
Summary
Constructor overloading means having multiple constructors with different inputs.
It allows creating objects in different ways depending on what information you have.
Each constructor must have a unique list of parameters.