views:

202

answers:

2

What do i write instead of ??????? to select proper overload?

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class A {}

    class B : A {}

    class C : A {}

    class Program
    {
     static void Main(string[] args)
     {
      var l1 = new List<C>();
      var l2 = new List<C>();
      Comparer<C>(l1, l2, ???????);
     }

     void Compare(C a, C b) { }

     void Compare(B a, B b) {}

     void Compare<T>(IList<T> a, IList<T> b, Action<T,T> comparator)
     {
      for (int i = 0; i < a.Count; i++)
       comparator(a[i], b[i]);
     }
    }
}
A: 

That depends on what you want to do with the values. If you just want to pass a delegate you could do the following

Comparer<C>(l1,l2, (left,right) => {});

In this case, the <C> part can actually be left off. The compiler will be able to infer the parameters.

I am curious about your choice of Action<T,T> for the parameter named comparer. Comparison functions typically return a value which represents the result of comparing two values. The Action<T,T> type just returns void. It should likely be either

  1. Changed to Func<T,T,int> which is a more standard signature for a comparison function
  2. Change the parameter name to something more indicitive of a function that doesn't return a value. Like del, action or func.
JaredPar
+3  A: 

You just need to make the methods static and fix the method name. You can even use type inference on the initial call to Compare:

static void Main(string[] args)
{
    var l1 = new List<C>();
    var l2 = new List<C>();

    Compare(l1, l2, Compare);
}

static void Compare(C a, C b) {}

static void Compare(B a, B b) {}

static void Compare<T>(IList<T> a, IList<T> b, Action<T,T> comparator)
{
    for (int i = 0; i < a.Count; i++)
        comparator(a[i], b[i]);
}

In this case there's no ambiguity - Compare(C, C) is the only method in the group which is convertible to an Action<C, C>. If you had a Compare(A, A) method, the more specific method would still be picked. You'd get ambiguity if instead you had:

static void Compare(A a, C b) {}
static void Compare(C a, A b) {}

However, I would strongly recommend that in cases like this you try to avoid overloading where possible. Give the methods distinct names - it'll make it a lot easier to read, and avoid any ambiguity.

Jon Skeet
Thanks, my bad!
UserControl