Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 850
Valentin Kuzub Avatar asked Dec 04 '11 11:12

Valentin Kuzub


People also ask

What do code contracts do?

Code Contracts provide a language-agnostic way to express coding assumptions in . NET programs. The contracts take the form of preconditions, postconditions, and object invariants.

Which method of the contract class is used to implement precondition contracts?

You can express preconditions by using the Contract. Requires method. Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values.

What is contract class in C#?

Abstract: Code Contracts API includes classes for static and runtime checks of code and allows you to define preconditions, postconditions, and invariants within a method. The Contracts class is found in the System. Diagnostics namespace.


1 Answers

For that purpose the [Pure] Attribute has been added to the System.Diagnostic.Contracts Namespace. See here for further explanation. However you cannot prevent a single property from being changed. The method is not allowed to change the object state at all (like the C++ const).

EDIT: Unfortunately the Pure attribute does not work with the current tools. I implemented a test with the following code, no error message either at static nor at runtime type checking:

public class Test
{
    private int x = 0;

    [Pure]
    public void Foo()
    {
        x++;
    }
}

Regarding to the documentation of Pure checks will be supported 'in the future'. Whenever that is ("The Code Contracts team is working heavy on that, thus to come up with a purity checker in a future release.").

I have been using the attribute in the believe it works properly. The documentation says that all methods called within a contract must be declared as pure. It doesn't say whether that's checked or not.

So the answer to your question is: There is no current support for this, but may be in the future.

like image 165
slfan Avatar answered Sep 20 '22 22:09

slfan