Hi,
There are two ways to implement overloads. The first one is to do everything in one method/constructor and call it from other overloads, which leads to longer method bodies. The second one is to do the minimum in each overload, thus having a code sometimes difficult to navigate and to understand which overload does what.
For example, if two overloads of a class Cat
are:
public Cat(string name, int? weight, Color mainColor);
public Cat(string name);
there are two ways to implement this:
First type
public Cat(string name, int? weight, Color mainColor)
{
// Initialize everything.
this.name = name;
if (weight.HasValue) this.weight = weight.Value;
// There is a bug here (see the anwer of @Timwi): mainColor can be null.
this.colors = new List<Colors>(new[] { mainColor });
}
public Cat(string name)
: this(name, null, null)
{
// Nothing else to do: everything is done in the overload.
}
Second type
public Cat(string name)
{
// Initialize the minimum.
this.name = name;
this.colors = new List<Colors>();
}
public Cat(string name, int? weight, Color mainColor)
: this(name)
{
// Do the remaining work, not done in the overload.
if (weight.HasValue) this.weight = weight.Value;
this.colors.Add(mainColor);
}
Questions
- How those two types of overloads are called (to be able to look for further information on internet or in books)?
- What must be the major concerns/factors to take in account when choosing between those types?
Note: since C# 4.0 let you specify optional parameters, to avoid ambiguity, let's say I'm talking about C# 3.0 only.