Search code examples
c#code-contracts

Is it possible to specify code contracts to ensure that method doesn't change state of object


Lets say I got a boolean IsValid property on my object.

I would like to create a method, and ensure that IsValid isn't changed after calling it, whether it was true or false before the call.

Is there a support for such thing?


Solution

  • I haven't tried it myself, but according to the MSDN Contract.OldValue might help to check that a single property value has not changed:

    public bool IsValid
    {
      get
      {
        ...
      }
    }
    
    public void SomeMethod()
    {
      Contract.Ensures(this.IsValid == Contract.OldValue(this.IsValid));
      ...
    }