views:

39

answers:

2

The following code gives me the warning Contract class 'FooContracts' should be an abstract class. From all the examples I've read online (e.g. http://www.infoq.com/articles/code-contracts-csharp), this should work (presumably without compiler warnings).

[ContractClass(typeof(FooContracts))]
public interface IFoo {
  void Bar(string foo);
}

[ContractClassFor(typeof(IFoo))]
internal sealed class FooContracts : IFoo {
  void IFoo.Bar(string foo) {
    Contract.Requires(foo != null);
  }
}

I'm in Visual Studio 2010, with the following settings in the Code Contracts section of the project's properties:

  • Perform Runtime Contract Checking (set to Full)
  • Perform Static Contract Checking (under Static Checking)
  • Check in Background

I also defined the CONTRACTS_FULL compilation symbol to make ReSharper shut up.

Am I missing something to make this compile without warnings?

+3  A: 

Section 2.8 of the code contracts manual specifically states that it should be an abstract class:

The tools expect that the contract class is abstract and implements the interface it is providing contracts for.

Rich
huh. thanks for the link. that fact was never mentioned nor demonstrated in any example code i found.
tmont
A: 

Most likely the InfoQ article you are referencing is incorrect. It's based on an "early access" edition of C# in Depth, so the code contracts implementation probably changed between the time the chapter/article was originally written and .NET 4 was released.

The following code should work:

[ContractClass(typeof(FooContracts))] 
public interface IFoo { 
  void Bar(string foo); 
} 

[ContractClassFor(typeof(IFoo))] 
internal abstract class FooContracts : IFoo { 
  void IFoo.Bar(string foo) { 
    Contract.Requires(foo != null); 
  } 
}

The contract class must be abstract.

Scott Dorman