I'm learning about code contracts in .NET, and I'm trying to understand the idea of pure constructors. The code contracts documentation states:
All methods that are called within a contract must be pure; that is, they must not update any preexisting state. A pure method is allowed to modify objects that have been created after entry into the pure method.
And the PureAttribute
documentation states:
Indicates that a type or method is pure, that is, it does not make any visible state changes.
I understand these statements when it comes to methods, but what about constructors? Suppose you had a class like this:
public class Foo
{
public int Value { get; set; }
public Foo(int value) {
this.Value = value;
}
}
This constructor obviously does affect the state of the new Foo
object, but it has no other side effects (e.g. it doesn't manipulate any of the parameters or call any non-pure methods). Is this a candidate for [Pure]
or not? What is the significance of placing a [Pure]
attribute on a constructor, and when should I do this in my own code?