The following pattern is common in my code: A class has several constructors. One is the "designated constructor", the others are for convenience. The code may look like this:
class Foo
{
Foo(int bar, string baz)
{
this.Bar = bar;
this.Baz = baz;
}
Foo()
: this(0, "Empty baz")
{
}
Foo(Foo f)
: this(f.Bar, f.Baz)
{
}
int Bar {get;set;}
string Baz {get;set;}
}
In the case of the parameterless constructor calling this(...), this works fine. However, if someone passes null as an argument to the copy constructor Foo(Foo), the result will be an null reference exception because of the expression f.Bar. Because I would like to see an ArgumentNullException instead, I usually stray from the pattern in cases like this and implement the constructor "manually", which results in duplicate code. Is there an elegant way to avoid this, i.e. having one designated constructor and still perform parameter validation for the others?
Edited: This example is bare-bones just to describe the issue. In real-world examples, there will be more complex argument validation logic and initialization code.