The class of the contract must be an abstract class.

The following code gives me a warning Contract class 'FooContracts' should be an abstract class . Of all the examples I've read on the Internet (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 am in Visual Studio 2010 with the following settings in the Code Contracts section of the project properties:

  • Performing a runtime execution check (set to Full )
  • Performing a static contract check (under Static Checking )
  • Background check

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

Am I missing something to make this compilation without warning?

+7
abstract-class code-contracts
source share
2 answers

Section 2.8 of the contract manual states that it should be an abstract class:

Tools expect the contract class to be abstract and implement the interface that it provides the contracts for.

+9
source share

Most likely, the InfoQ article you are linking to is incorrect. This is based on the "early access" of the C # edition of Depth, so the implementation of code contracts has probably changed between how 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 class of the contract must be abstract.

+3
source share

All Articles