So ran into this today and the answer was actually a lot easier to understand than I thought it would be.
Say you want to order a list of objects by a number. Seems simple. Now if you have been paying attention you would know I like using Funcs.
Func<SomeClass, Int32> orderByNumber = currentClass => currentClass.SomeNumber; anotherCollection = someCollection.OrderBy(orderByNumber);
Seems simple, but what if you wanted to use a method already defined in the class?
private Int32 ReturnNumber(SomeClass currentClass) { return currentClass.SomeNumber; }
It seems like this could be the way to go, right?
someCollection.OrderBy(ReturnNumber);
Compile and BOOOOOOM you get an error. It says it can’t infer the return type of the method. Wait what? It’s pretty obvious right, it’s an integer. It had no problem inferring from the Func and you have to figure that the method itself is “typed” also. Well here’s the problem (And you’re dumb for not knowing this, but I’m not because I’m immune to dumb), ReturnNumber isn’t a method, it’s part of a method group. You can have a million (well maybe not that many) methods named ReturnNumber, all with different parameters. Why is this a problem? Well let’s use lambda expressions:
someCollection.OrderBy(currentClass => currentClass.SomeNumber);
At this point it knows two things: currentClass is a SomeClass and there is a Method that takes in a SomeClass and returns something. So with that in mind, it looks for such a method and finds the return type. This is no different with the Func since the Func is basically unique due to it being a named field. After all you can’t have two fields named orderByNumber, but you can have many methods named ReturnNumber. That is where the problem is. When you use the second example:
someCollection.OrderBy(ReturnNumber);
It can infer the SomeClass from the list and it sees the method. For there it has to find the method’s return type. Wait, which method? If i Have 10 overloads, each with different return types, how does it know what type to use? Well the answers is, it doesn’t. So basically you’re screwed. Sucks, huh?
Side note: This works
Func<SomeClass, Int32> orderByNumber = ReturnNumber;