Consider the following class:
public class TwoWayMap<T1, T2>
{
public T2 Get(T1 x)
{
throw new System.NotImplementedException();
}
public T1 Get(T2 x)
{
throw new System.NotImplementedException();
}
}
If T1 and T2 are different types and we call Get
, then the compiler knows which one we mean.
var map1 = new TwoWayMap<int, string>();
map1.Get("hello");
map1.Get(5);
However, if the types are equal, then the two methods share the same signature. And in terms of overload resolution, they are equally specific (compared to, say, a generic vs a non-generic parameter). Therefore, we cannot call the method unambiguously.
var map2 = new TwoWayMap<int, int>();
map2.Get(5);
Compiler Error CS0121: The call is ambiguous between the following methods or properties: 'TwoWayMap.Get(T1)' and 'TwoWayMap.Get(T2)'
Of course, we can (and should) avoid this issue by not using equal types or by providing dedicated Get1
and Get2
methods, but I am wondering: Is there some way in C# or .NET to disambiguate this? Is it possible to call map2.Get()
?