Search code examples
c#genericsinterfacecode-contracts

Nested contracts for generic interfaces


I can have a nested contracts type for a non-generic interface:

[ContractClass(typeof(Foo.FooContracts))]
public interface IFoo
{
    string Bar(object obj);
}

But it complains when I try to do the same thing with a generic interface:

[ContractClass(typeof(Foo.FooContracts<>))]
public interface IFoo<T>
{
    string Bar(T obj);
}

The warning is:

The contract class Foo+FooContracts`1 and the type IFoo`1 must have the same declaring type if any.

It compiles without a warning if I get FooContracts out of the Foo class.

  • Why does that limitation exist for generic interfaces?
  • Why doesn't that limitation exist for non-generic ones?

Solution

  • The reason the limitation exists is that we need to copy contracts from the declaration point to the insertion points and that gets much more complicated if there are generic surrounding classes. There really is no need to have contract classes nested inside other types that I see.