I'd like to enforce a struct to always be valid regarding a certain contract, enforced by the constructor. However the contract is violated by the default
operator.
Consider the following, for example:
struct NonNullInteger
{
private readonly int _value;
public int Value
{
get { return _value; }
}
public NonNullInteger(int value)
{
if (value == 0)
{
throw new ArgumentOutOfRangeException("value");
}
_value = value;
}
}
// Somewhere else:
var i = new NonNullInteger(0); // Will throw, contract respected
var j = default(NonNullInteger); // Will not throw, contract broken
As a workaround I changed my struct to a class so I can ensure the constructor is always called when initializing a new instance. But I wonder, is there absolutely no way to obtain the same behavior with a struct?