I recently wrote this and was surprised that it compiles:
public class MyGeneric<U, V> {
MyGeneric(U u) { ... }
MyGeneric(V v) { ... }
public void Add(U u, V v) { ... }
public void Add(V v, U u) { ... }
}
If I use this class as follows, I get an "Ambiguous constructor reference" and an "Ambiguous invocation" if I call Add.
var myVar = new MyGeneric<int, int>(new MyIntComparer());
Obviously, there's no ambiguity when I use int and double as generic types, except of course when I use both ints, which would also both assign to a double.
var myVar = new MyGeneric<int, double>(new MyIntComparer());
myVar.Add(3, 5);
So then I thought that the following was also allowed, but surprisingly I got an error. Why is the following not allowed to compile?
public interface IMyInterface<T, S> {
void Add(T t, S s);
}
public class MyGeneric<U, V> : IMyInterface<U, V>, IMyInterface<V, U> {
public MyGeneric(U u) { }
public MyGeneric(V v) { }
void IMyInterface<U, V>.Add(U u, V v) { ... }
void IMyInterface<V, U>.Add(V v, U u) { ... }
}
Regardless if I use implicit or explicit interface implementation, the compiler states that
'MyGeneric<U,V>' cannot implement both 'IMyInterface<U,V>' and 'IMyInterface<V,U>' because they may unify for some type parameter substitutions
And why is the first allowed to write?