Possible Duplicate:
Generic methods and method overloading
Say I have a class like
class SortedList<K>
{
public string this[int i] { get { return "a"; /* dummy sample code */ } }
public string this[K key] { get { return "b"; /* dummy sample code */ } }
}
Now let's say some dude decides to use it:
static string Test1<K>(K key) { return new SortedList<K>()[key]; }
The compiler resolves this call to the K key
overload.
Now, contrast this with saying
static string Test2(int key) { return new SortedList<int>()[key]; } // whoops
where the compiler resolves this to the int i
overload.
Now if some poor soul says Test1(0)
, he'll get a different result then if he says Test2(0)
, even though the bodies look pretty much identical at first glance.
The funnier thing is, in neither case does the compiler or runtime detect an ambiguity and give an error.
Instead, the runtime just changes its behavior with respect to whether the value is generic or not, which can be clearly unexpected for the caller.
Why is the behavior inconsistent?
Or, better yet, why is there no compiler (or runtime) error because of the ambiguity?