Search code examples
.net-4.0code-contracts

Code Contract understanding of error


I am just getting started with Code Contracts, and need a little help in correcting an error:

Given this code:

class MyClass
{
    private bool _isUsed = false;

    public void SomeMethod()
    {
        Contract.Requires(!_isUsed);
    }
}

I get the following error:

error CC1038: Member 'MyClass._isUsed' has less visibility than the enclosing method 'MyClass.SomeMethod'

which seems to makes alot of the standard checks unavailable. What am I missing in this example?


Solution

  • You have a public method SomeMethod. However, you're requiring that a private member variable is set to false. You provide no way of setting _isUsed, and so you're putting a check on a variable that a caller has no control over.

    You could make _isUsed into a property i.e.

    public bool IsUsed {get; set;}
    

    And then in your SomeMethod() have

    Contract.Requires(!IsUsed);