My current non-compiling code is similar to this:
public abstract class A { }
public class B { }
public class C : A { }
public interface IFoo<T>
{
void Handle(T item);
}
public class MyFoo<TA> : IFoo<TA>, IFoo<B>
where TA : A
{
public void Handle(TA a) { }
public void Handle(B b) { }
}
The C# compiler refuses to compile this, citing the following rule/error:
'MyProject.MyFoo<TA>' cannot implement both 'MyProject.IFoo<TA>' and 'MyProject.IFoo<MyProject.B>' because they may unify for some type parameter substitutions
I understand what this error means; if TA could be anything at all then it could technically also be a B which would introduce ambiguity over the two different Handle implementations.
But TA can't be anything. Based on the type hierarchy, TA can't be a B - at least, I don't think it can. TA must derive from A, which does not derive from B, and obviously there's no multiple class inheritance in C#/.NET.
If I remove the generic parameter and replace TA with C, or even A, it compiles.
So why do I get this error? Is it a bug in or general un-intelligence of the compiler, or is there something else I'm missing?
Is there any workaround or am I just going to have to re-implement the MyFoo generic class as a separate non-generic class for every single possible TA derived type?
What's stopping you from passing the same thing to type parameter `B` as you pass to `TA`?– Josh Oct 05 '11 at 17:00