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;
-
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 (likeSelect
orOrderBy
projections), the compiler won't infer the appropriate delegate conversion. -
ReturnNumber
is not a method - instead, it represents a method group containing all methods with the nameReturnNumber
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))
Programmin Tool : Method group is something I wasn't thinking about. Wish I could mark two answers.
0 comments:
Post a Comment