0

My method signatures are the same except for the first parameter.

public DataSet MyMethod(IEnumerable<T> list)
{
}


public DataSet MyMethod(T obj)
{
}

Calling method is :

List<myobject> _objlist = new List<myobject>();

DataSet ds = MyMethod(_objlist );

I expect the first method to be called but the second one is being called instead? Isn't the IEnumerable more specific to the List being passed as compared to the more generic object?

Max
  • 97
  • 2
  • 13
  • 2
    What is T, does it have any constraint on the class itself? – Johnny Oct 01 '19 at 06:41
  • 1
    Your code is not valid C#. Please give us the actual code sample. – V0ldek Oct 01 '19 at 06:42
  • 1
    Well, in case where multiple overloads are valid the runtime choses the best fit, which is the most specific one. In your case `T`matches perfectly, while `IEnumerable` matches less, as you have to implictely convert your list to an enumerable. – MakePeaceGreatAgain Oct 01 '19 at 06:44
  • 1
    @Cid, sorry I couldn't copy out the actual code. My bad, fixed it. – Max Oct 01 '19 at 06:45
  • its still not valid code MyMethod(T object) will not compile as object is a reserved word – Tim Rutter Oct 01 '19 at 06:46
  • Question closed as duplicate but I don't think it helps the OP. Simple answer: It is because the compiler search in type hierarchy from bottom to top, first in the class hierarchy, then in the interface hierarchy as classes primes on interfaces. Indeed, before being of type of an interface, an object is of type of a class first of all. To have the correct call, you should cast the instance to the interface type you want act on and write: DataSet ds = MyMethod((IEnumerable)_objlist); –  Oct 01 '19 at 06:53
  • Thanks @OlivierRogier, but since the _objlist is a List type which is Enumerable, why isn't the first version of the method called? – Max Oct 01 '19 at 06:54
  • 2
    @OlivierRogier The answer from the dupe is: compiler choses the most specific overload. `T` is surely more specific than `IEnumerable` here. – MakePeaceGreatAgain Oct 01 '19 at 06:55
  • 1
    As I said, class primes over interface. List is a class before being an interface. And the call is made passing a class reference, not an interface reference. –  Oct 01 '19 at 06:58
  • Hope this can help you to understand: https://stackoverflow.com/questions/32892243/which-c-sharp-method-overload-is-chosen/58180919#58180919 –  Oct 01 '19 at 08:33

0 Answers0