Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Contracts: How do I supply a contract class for a generic interface?

I'd like to specify a contract for this generic interface, using Code Contracts:

interface IRandomWriteAccessible<T> {     T this[uint index] { set; }     uint Length { get; } } 

The documentation says to use the ContractClass attribute when specifying a contract for an interface. However, the compiler will complain about this:

[ContractClass(typeof(IRandomWriteAccessibleContract<T>))] //             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^     <-- compiler error interface IRandomWriteAccessible<T> { … }  [ContractClassFor(typeof(IRandomWriteAccessible<T>))] //                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^          <-- compiler error sealed class IRandomWriteAccessibleContract<T> : IRandomWriteAccessible<T> { … } 

It seems that type parameters cannot be used with attributes.

How do I write a contract for my generic interface? Or is this not possible with Code Contracts?

like image 456
stakx - no longer contributing Avatar asked Jan 27 '10 23:01

stakx - no longer contributing


People also ask

Can a generic type be an interface?

Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

What are code contracts C#?

Code Contracts provide a language-agnostic way to express coding assumptions in . NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs.


2 Answers

As mentioned by other comments in this question, you should remove the generic type identifier from your attribute usage as it can not be resolved at compile time:

[ContractClass(typeof(IRandomWriteAccessibleContract<>))]  
like image 183
Steve Guidi Avatar answered Sep 18 '22 05:09

Steve Guidi


Good question, but you can see the technical reasons behind this limitation, right?

The reason that you can't specify the ContractClass is because Blah<T> is not a class.

If you can make an interface for a concrete class by specifying a value for T, even though I'm sure this is sub-optimal.

like image 43
John Gietzen Avatar answered Sep 22 '22 05:09

John Gietzen