Consider the contravariant interface definition with a delegate:
public interface IInterface<in TInput>
{
delegate int Foo(int x);
void Bar(TInput input);
void Baz(TInput input, Foo foo);
}
The definition of Baz fails with an error:
CS1961
Invalid variance: The type parameter 'TInput' must be covariantly valid on 'IInterface<TInput>.Baz(TInput, IInterface<TInput>.Foo)'. 'TInput' is contravariant.
My question is why? On first glance this should be valid, as the Foo delegate has nothing to do with TInput. I don't know if it's the compiler being overly conservative or if I'm missing something.
Note that normally you wouldn't declare a delegate inside an interface, in particular this doesn't compile on versions older than C# 8, since a delegate in an interface needs default interface implementations.
Is there a way to break the type system if this definition was allowed, or is the compiler conservative?
I am not sure if this is co- versus contravariance problem.
Foo delegate is not a member of the interface. It is a nested type declaration.IInterface<A>.Foo and IInterface<B>.Foo are two different types.foo parameter of two different IInterface<T>.Baz methods (with T = A and B) incompatible.IInterface<A> for a IInterface<B> or vice-versa (no matter what the inheritance relationship between A and B is.IInterface<T> cannot be variant (neither co- nor contra-).Resolution:
IInterface for this (and keep your generic one).But @EricLippert certainly knows better.