Search code examples
c#overloading

Two extension methods with ambiguous signature


public static string AddRange(this List<Parameter> parameters, string name, object[] values)
{
    ...
}

public static string AddRange(this List<Parameter> parameters, string name, IEnumerable<object> values)
{
    return parameters.AddRange(name, values.ToArray());
}

This combination, when called like this:

SomeFunction(params string[] keys)
{
    ...
    parameters.AddRange("paramKeys", keys);
    ...
}

throws

The call is ambiguous between the following methods or properties: 'ExtensionMethods.AddRange(List, string, object[])' and 'ExtensionMethods.AddRange(List, string, IEnumerable)'

I know roughly why this is thrown (an Array also is an IEnumerable), but I don't know how to fix it without removing any of the two methods. How can I tell the IEnumerable<object> method that it is not responsible for arrays, but for all other kinds of IEnumerable<object>?


Solution

  • You have the problem because a string[] is type of IEnumerable but also is the type of an object[] (Since all reference types derive from object).

    What you need to do is cast it to the correct type that the extension method is expecting:

    parameters.AddRange("paramKeys", (object[])keys);
    // OR
    parameters.AddRange("paramKeys", (IEnumerable<object>)keys);