views:

914

answers:

2

So odd situation that I ran into today with OrderBy:

Func<SomeClass, int> orderByNumber = 
  currentClass => 
   currentClass.SomeNumber;

Then:

someCollection.OrderBy(orderByNumber);

This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy.

private int ReturnNumber(SomeClass currentClass)
{
  return currentClass.SomeNumber;
}

Now when I try to plug that into the OrderBy:

someCollection.OrderBy(ReturnNumber);

It can't infer the type like it can if I use a Func. Seems like to me they should be the same since the method itself is "strongly typed" like the Func.

Side Note: I realize I can do this:

Func<SomeClass, int> orderByNumber = ReturnNumber;
+7  A: 

This could also be related to "return-type type inference" not working on Method Groups.

Essentially, in cases (like Where's predicate) where the generic parameters are only in input positions, method group conversion works fine. But in cases where the generic parameter is a return type (like Select or OrderBy projections), the compiler won't infer the appropriate delegate conversion.

Jacob Carpenter
+7  A: 

ReturnNumber is not a method - instead, it represents a method group containing all methods with the name ReturnNumber but with potentially different arity-and-type signatures. There are some technical issues with figuring out which method in that method group you actually want in a very generic and works-every-time way. Obviously, the compiler could figure it out some, even most, of the time, but a decision was made that putting an algorithm into the compiler which would work only half the time was a bad idea.

The following works, however:

someCollection.OrderBy(new Func<SomeClass, int>(ReturnNumber))
Justice
Method group is something I wasn't thinking about. Wish I could mark two answers.
Programmin Tool