-1
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>?

Alexander
  • 19,906
  • 19
  • 75
  • 162
  • 4
    Why do you have two overloads in the first place? – Servy Aug 09 '16 at 15:51
  • You can just cast to the one you want `parameters.AddRange("paramKeys", (object[])keys)` – Lee Aug 09 '16 at 15:55
  • 1
    I am not getting any compilation error with Visual Studio 2015. Is it due to C# 6.0's [Improved overload resolution](https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6)? – Olivier Jacot-Descombes Aug 09 '16 at 16:07
  • See also https://stackoverflow.com/questions/26606199/ambiguous-call-between-overloads-of-two-way-implicit-castable-types-when-a-deriv and https://stackoverflow.com/questions/1451099/how-to-override-an-existing-extension-method for useful discussion of overload resolution in general, as it applies to these types of ambiguous scenarios. – Peter Duniho Aug 09 '16 at 17:20

1 Answers1

2

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jamie Rees
  • 7,973
  • 2
  • 45
  • 83