I've been playing around with constructors and noticed in most code overloaded constructors are:
public class ClassFirst
{
public string Name { get; set; }
public int Height { get; set; }
public int Weight { get; set; }
public ClassFirst(string name, int height, int weight)
{
Name = name;
Height = height;
Weight = weight;
}
public ClassFirst(string name)
: this(name, 0, 0)
{ }
public ClassFirst(string name, int height)
: this(name, height, 0)
{ }
}
Which I would call 'underloading' instead of overloading, because the added constructors chip away at the full constructor... and seems to be used much more than the way I intuitively want to overload, which is ->
public class ClassSecond
{
public string Name { get; set; }
public int Height { get; set; }
public int Weight { get; set; }
public ClassSecond(string name)
{
Name = name;
}
public ClassSecond(string name, int height): this (name)
{
Height = height;
}
public ClassSecond(string name, int height, int weight): this (name, height)
{
Weight = weight;
}
}
Why are the constructors is used like that? There must be advantages...
Answer: below is a great example of how to concisely write overloaded constructors in .net 4.0 using default parameters.
Previous Stack Overflow Answer: I found there is a previous question that addresses constructor overloads: C# constructor chaining? (How to do it?)