I have the following scenario:
public interface ISomething
{
void DoStuff();
//...
}
public class Something : ISomething
{
private readonly ISomethi
Section 3: Contract Inheritance of the user manual states that all preconditions must be defined in the root method of an inheritance/implementation chain:
If a client makes sure that they have satisfied the precondition and has a variable
o
whose static type isT
, then the client should not get a precondition violation when they callo.M
. This needs to be true even if the runtime valueo
has typeU
. Therefore, the methodU.M
cannot add a precondition that is stronger than the precondition ofT.M
.While we could allow a weaker precondition, we have found that the complications of doing so outweigh the benefits. We just haven't seen any compelling examples where weakening the precondition is useful. So we do not allow adding any preconditions at all in a subtype.
As a consequence, method preconditions must be declared on the root method of an inheritance/implementation chain, i.e., the first virtual or abstract method declaration, or the interface method itself.
In your situation, the best course of action is to set up an invariant stating that the _somethingElse
field is never null:
[ContractInvariantMethod]
private void ObjectInvariant() {
Contract.Invariant(_somethingElse != null);
}
This is of course always true, as the field is marked readonly
and initialised in the constructor. The static checker isn't able to infer this on its own though, so you must explicitly tell it through that invariant.
You can optionally add a postcondition Contract.Ensures(_somethingElse != null);
to your constructor, but the static checker doesn't require it.