My class has two private fields and three constructors.
One constructor is a default constructor that does not assign any values.
The remaining constructors each instantiate one of two fields, ensuring that one field is always null
and the other field is never null
.
public class MyClass
{
private readonly Foo foo;
public Foo InstanceOfFoo { get { return this.foo; } }
private readonly Bar bar;
public Bar InstanceOfBar { get { return this.bar; } }
// Default constructor: InstanceOfFoo == null & InstanceOfBar == null
public MyClass()
{
}
// Foo constructor: InstanceOfFoo != null & InstanceOfBar == null
public MyClass(Foo foo)
{
Contract.Requires(foo != null);
this.foo = foo;
}
// Bar constructor: InstanceOfFoo == null & InstanceOfBar != null
public MyClass(Bar bar)
{
Contract.Requires(bar != null);
this.bar = bar;
}
}
Now I need to add a class invariant method that specifies that InstanceOfFoo
and InstanceOfBar
are mutually exclusive: both can be null
, but only one of them can be something other than null
.
How do I express that in code?
[ContractInvariantMethod]
private void ObjectInvariant()
{
// How do I complete this invariant method?
Contract.Invariant((this.InstanceOfFoo == null && this.InstanceOfBar == null) || ...);
}
It looks like simple OR should be enougth:
Contract.Invariant(this.InstanceOfFoo == null || this.InstanceOfBar == null);
Proof (for someone, who downvoted :)
1. (null, null): true || true -> true
2. (inst, null): false || true -> true
3. (null, inst): true || false -> true
4. (inst, inst): false || false -> false