Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code contracts on auto-implemented properties

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)

like image 365
wh1t3cat1k Avatar asked Apr 01 '11 13:04

wh1t3cat1k


People also ask

Which statements apply to auto implemented property?

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.

What are the code contracts?

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.

What is true about auto implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

What is implemented 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#.


2 Answers

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 setter, 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:

  1. A precondition for the setter
  2. A postcondition for the getter
  3. 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 );
...
like image 172
StuartLC Avatar answered Oct 14 '22 08:10

StuartLC


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.

like image 41
BrandonZeider Avatar answered Oct 14 '22 09:10

BrandonZeider