Search code examples
c#objectmethodsoverloadingienumerable

C#, overload for single T and for IEnumerable<T>


public static void AddOrUpdate<T>(T entry) where T : class
{
        //stuff
}

public static void AddOrUpdate<T>(IEnumerable<T> entries) where T : class
{
    foreach (var entry in entries)
    {
        //stuff
    }

No matter what I send into this method, the first one is always chosen. How do I separate IEnmuerables and single objects?

AddOrUpdate(entry); //goes into first one
AddOrUpdate(new Analog[] { entry}); //still goes into first one

Solution

  • Because the definition of the first overload states that the argument of the method is of the same type as its generic argument (both are of type T) whenever you call the method without explicitly pointing the generic argument (AddOrUpdate(new Analog[] { entry })) the compiler decides that the types match - AddOrUpdate<Analog[]>(new Analog[] { entry }). You need to explicitly point the generic argument in order to help the compiler choose the correct overload:

    AddOrUpdate<Analog>(new Analog[] { entry });