MaYaN MaYaN - 3 months ago 17
C# Question

Why is this C# method overloading not working as expected?

I have the following methods:

public void Say<TItem>(TItem item)
{
Console.WriteLine("A");
}

public void Say<TItem>(IEnumerable<TItem> items)
{
Console.WriteLine("B");
}


When I run the following:

void Main()
{
Say<string>("Foo");
Say(new string[] { "Foo", "Bar"});

}


The first method is invoked twice:

A
A


Note changing the
IEnumerable<T>
to a
TItem[]
does work as expected but in the case of the
IEnumerable<T>
why is it not picking up the second method? How can I achieve the intended overloading?

Answer

Because it thinks that TItem is string[]. Look at this from the perspective of the compiler: All it knows is that it is looking for a generic type to plug into that method. It just so happens that string[] is a type. Because the meaning here is potentially ambiguous, you need to give the compiler some help to select which overload you are looking for here:

Say<string>(new string[]{"Foo", "Bar"});

should be enough to get it to select the method you actually wanted.