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.
Nested contracts for generic interfaces
-
29-06-2022 - |
Question
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 typeIFoo`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
OTHER TIPS
This code compiles on my machine (VS2012, .NET 4.5)
[ContractClass(typeof(Foo.FooContracts<>))]
public interface IFoo<T> {
string Bar(T obj);
}
[ContractClassFor(typeof(IFoo<>))]
public class Foo {
public class FooContracts<T> : IFoo<T> {
public string Bar(T obj) {
throw new NotImplementedException();
}
}
}
I added the ContractClassForAttribute, but I can take it out.
edit: also the ContractClassForAttribute can be applied to the outer or inner class. I don't know which is correct, but neither location affects compilation
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow