views:

93

answers:

2

Consider the following code :

public class RandomClass
{        
    private readonly string randomString;

    public RandomClass(string randomParameter)
    {
        Contract.Requires(randomParameter != null);
        Contract.Ensures(this.randomString != null);

        this.randomString = randomParameter;
    }

    public string RandomMethod()
    {
        return  // CodeContracts: requires unproven: replacement != null
            Regex.Replace(string.Empty, string.Empty, this.randomString);
    }
}

This ensures that randomString will not be null when RandomMethod gets executed. Why does code contracts analysis ignores this fact and throws a CodeContracts: requires unproven: replacement != null warning?

+2  A: 

You should use type invariants for such cases

vc 74
+3  A: 

It is probably not so much that the analyzer ignores the fact that it is unable to make the link between the two methods.

The property "field randomString is non-null" is a class invariant: it is established at each instance creation, and trivially preserved on each method call because the field is read-only. I urge you to provide one stating just that. It will be easily verified by the analyzer and will provide the hypothesis necessary to prove that RandomMethod is safe.

This page has a good explanation about class invariants.

Pascal Cuoq
Thanks mate. Adding a `ContractInvariantMethod` solved the problem :)
Diadistis