Constructor overloading
Learn to define multiple constructors in the same class.
Constructor overloading
You can declare multiple constructors in a class; this is called overloading. Each constructor must have a different parameter signature: different number of parameters or different types.
Example: an Order class can have both public Order() and public Order(string customer). The compiler picks the right one based on the call. This gives the caller flexibility: callers with full information use the detailed constructor, others use the simple one.
Resolution
When you write new, the compiler compares your arguments to each constructor's parameter signature and picks the single match. The call new Order("Alex") goes to the constructor that takes a string.
If no constructor matches, you get a compile error. If multiple constructors match ambiguously, you also get an error; for instance, with constructors taking int and double, new Sample(5) can be ambiguous. Keeping signatures clear prevents this.
Exercise Add two overloaded constructors to Order
Add public string Customer { get; set; } and public int Items { get; set; } properties to the Order class. Declare two constructors: a parameterless one that sets Customer = "Unknown"; Items = 0;, and one taking string customer and int items that assigns them to the properties. Inside Main create an instance with new Order("Alex", 3) and print Customer.
Show example solution
parameterless and two-parameter. In Main write Order o = new Order("Alex", 3); Console.WriteLine(o.Customer);
Example solution:
using System;
class Order
{
public string Customer { get; set; }
public int Items { get; set; }
public Order()
{
Customer = "Unknown";
Items = 0;
}
public Order(string customer, int items)
{
Customer = customer;
Items = items;
}
}
class Program
{
static void Main()
{
Order o = new Order("Alex", 3);
Console.WriteLine(o.Customer);
}
}
Test yourself
-
Match each call to its constructor
- new Order()
- Parameterless constructor
- new Order("Alex")
- One-parameter constructor
- new Order("Alex", 3)
- Two-parameter constructor
- Order()
- Not a call alone
-
Complete the overload call
Order o = new Order("____", 3);Show answer
Order o = new Order("Alex", 3); -
When are two constructors considered overloads?
- Same parameters, different name
- Different access modifier
- Different parameter signature
- Same body
Show answer
Different parameter signature — Correct. Overloading requires different parameter signatures.