开发者

Code contracts problem

开发者 https://www.devze.com 2023-01-16 04:47 出处:网络
Consider the following code : public class RandomClass { private readonly string randomString; public RandomClass(string randomParameter)

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 ensure开发者_如何学Gos 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消