Overload resolution issue for generic method with constraints

Does compiler take into account type parameter constraints at all, when resolving overloads?

No, because generic constraints are not part of the function signature. You can verify this by adding a Bar overload that is identical except for the generic constraints:

interface IBar { }

static void Bar<T>(IEnumerable<T> value)
    where T : IFoo
{
}

static void Bar<T>(T source)
    where T : IBar
{
    // fails to compile : Type ____ already defines a member called 'Bar' with the same parameter types
}

The reason your code doesn’t compile is because the compiler chooses the “best” match based on the method signature, then tries to apply the generic constraints.

One possible reason why it doesn’t is because this call would be ambiguous:

{suppose List<T> had an Add<T>(IEnumerable<T> source) method}

List<object> junk = new List<object>();
junk.Add(1);   // OK
junk.Add("xyzzy") // OK
junk.Add(new [] {1, 2, 3, 4});  //ambiguous - do you intend to add the _array_ or the _contents_ of the array?

The obvious fix is to use a different name for the Bar method that takes a collection (as is done in the BCL with Add and AddRange.

Leave a Comment