Here is the problem illustrated using an example of an immutable class. A Book must have at least one of a title and an ISBN.
public class Book
{
private readonly string _title;
private readonly int? _isbn;
public Book(string title)
: this(title, null, true)
{
... throw exception if title is null
}
public Book(int isbn)
: this(null, isbn, true)
{
... throw exception if isbn < 1
}
public Book(string title, int isbn)
: this(title, isbn, true)
{
... throw exception if title is null
... throw exception if isbn < 1
}
private Book(string title, int? isbn, bool privateConstructor = true)
{
_title = title;
_isbn = isbn;
... more work (beyond the scope of this example)
}
... public properties, etc.
}
See that privateConstructor
boolean? I had to throw that in to differentiate between the public Book(string, int)
and the private Book(string, int?)
. While this is fairly harmless since the extraneous parameter is in a private constructor, its use seems smelly to me. Reordering the parameters of the private constructor would work but that would make the constructor initializers appear non-intuitive (in my real work, there's more than just two parameters in play). What is a better way?