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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With