Is there any way to put contracts on automatically implemented properties in .NET? (And how if the answer is 'Yes')?
(I assume using .NET code contracts from DevLabs)
Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.
Code contracts provide a way to specify preconditions, postconditions, and object invariants in . NET Framework code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits.
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.
The properties which do not require any code when used inside the get method and set method of the class are called Auto Implemented Properties in C#.
Yes, this is possible - all that is needed is to add your contract condition to the [ContractInvariantMethod]
method in your class, which then adds the equivalent Requires
precondition to the automatic set
ter, and a post condition Ensures
is added to the get
. From section 2.3.1 of the Reference
As the example illustrates, invariants on auto-properties turn into:
- A precondition for the setter
- A postcondition for the getter
- An invariant for the underlying backing field
And by example:
public int MyProperty { get; private set ;}
[ContractInvariantMethod]
private void ObjectInvariant ()
{
Contract.Invariant ( this.MyProperty >= 0 );
}
"Is equivalent to the following code:"
private int backingFieldForMyProperty;
public int MyProperty
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return this.backingFieldForMyProperty;
}
private set
{
Contract.Requires(value >= 0);
this.backingFieldForMyProperty = value;
}
}
[ContractInvariantMethod]
private void ObjectInvariant ()
{
Contract.Invariant ( this.backingFieldForMyProperty >= 0 );
...
I'm thinking not, but you could easily write a snippet that would do this. If you go this route, here is a free snippet editor that will make the task very easy.
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