Jannik
Jannik

Reputation: 2429

Overloading a generic extension method

I have a problem overloading an extension method.

I have two extension Methods:

Method A - For standard objects:

public static bool HasChanged<T>(this T obj1, T obj2, Func<T, T, bool> equalityExpression)

Method B - For IEnumerables:

public static bool HasChangedList<T>(this IEnumerable<T> obj1, IEnumerable<T> obj2, Func<T, T, bool> isEqualExpression)

But I would like to give them both the same names, that is currently not working, cause IEnumerables are objects aswell, so the compiler isnt able to decide whether to use the first one or the second one on an IEnumerable.

I am sure, its not possible to let first method take all object but an IEnumerable, so is there another way around?

Upvotes: 2

Views: 284

Answers (1)

Heinzi
Heinzi

Reputation: 172220

(Not really a solution, but too long for a comment. Hopefully, one of the C# spec gurus will show up and tell us why overload resolution works like this in this particular case.)

If

  • you qualify the parameters of your equalityExpression or if
  • the inner type of the IEnumerable can be inferred from the lambda expression,

it should work fine:

class Program
{
    static void Main(string[] args)
    {
        var array = new[] { 1, 2, 3 };

        // uses the IEnumerable overload -- prints false
        Console.WriteLine(array.HasChanged(array, (int x, int y) => x == y));

        // uses the IEnumerable overload -- prints false
        Console.WriteLine(array.HasChanged(array, (x, y) => x >= y));

        // uses the generic overload -- prints true
        Console.WriteLine(array.HasChanged(array, (x, y) => x == y));

        Console.ReadLine();
    }
}
static class Extensions
{
    public static bool HasChanged<T>(this IEnumerable<T> obj1, IEnumerable<T> obj2, Func<T, T, bool> isEqualExpression)
    { 
        return false; 
    }
    public static bool HasChanged<T>(this T obj1, T obj2, Func<T, T, bool> equalityExpression)
    { 
        return true; 
    }
}

Upvotes: 4

Related Questions