I know that this is supposedly a super simple question, but I\'ve been struggling with the concept for some time now.
My question is, how do you chain constructors
You use standard syntax (using this
like a method) to pick the overload, inside the class:
class Foo
{
private int id;
private string name;
public Foo() : this(0, "")
{
}
public Foo(int id, string name)
{
this.id = id;
this.name = name;
}
public Foo(int id) : this(id, "")
{
}
public Foo(string name) : this(0, name)
{
}
}
then:
Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");
Note also:
base(...)
base()
For "why?":
necessary to call a non-default base-constructor, for example:
SomeBaseType(int id) : base(id) {...}
Note that you can also use object initializers in a similar way, though (without needing to write anything):
SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
z = new SomeType { DoB = DateTime.Today };