If I have a class as below:
class MyClass<T,U>
{
public void DoSomething(T t)
{
}
public void DoSomething(U u)
{
}
}
But construct it using the same types (new MyClass<int,int>()
)
This compiles fine, but if I try to call DoSomething
it errors because of an ambiguous call, which of course is correct. But what if the method was called through reflection or some other dynamic way. I guess it would throw an exception at run time. So my question is why does the compiler allow me create this class with the same types if there's an exception waiting to happen?
The compiler is concerned with actual ambiguity and does not highlight any ambiguity related to overloading generic methods.
If you don't want to allow this, unfortunately there's no way to add a Generic Type Constraint, i.e. where T != U
, so you'll need to just throw an exception in the constructor:
public MyClass()
{
if (typeof(T) == typeof(U))
{
throw new Exception("T and U cannot be of the same type");
}
}
What you should do is use different names so that the two method names to not collide with one another. This is the safest way of working in this scenario:
public DoSomethingWithFirst()
{
// For T
}
public DoSomethingWithSecond()
{
// For U
}