7

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?

tmont
  • 2,562
  • 20
  • 15

2 Answers2

9

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
  • 3,081
  • 1
  • 22
  • 24
  • 1
    huh. thanks for the link. that fact was never mentioned nor demonstrated in any example code i found. – tmont Sep 04 '10 at 01:22
3

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
  • 42,236
  • 12
  • 79
  • 110
  • But making the class abstract means you can't new it after you implement the interface :( Any alternative around this? Other that creating a new concrete class that inherits from the abstract class? – Alex Bitek Dec 31 '13 at 10:47
  • 1
    @MnemonicFlow You shouldn't be creating instances of the contract class anyway. It's only for use by the Code Contracts engine. – piedar Feb 25 '16 at 21:53