While helping with the development of our Tasks application I stumbled upon a strange compiler error. There was a lambda expression that was compiling just fine before I touched the file with the lambda and after changing a line inside the body of the lambda, the project suddenly stopped compiling. The error was, that it could not find an adequate overload of the method that accepted the lambda in question as an argument. The cause turned out to be very interesting(for me at least) and I think it is worth sharing.
Consider that you have a function with two overloads that both accept a lambda but only one accepts another argument. Also consider that you have an empty test class. Once we have these we call one of the overloads and pass a lambda expression. For example:
Method(closedHandler: (eventArgs) =>
Notice how in our lambda expression we are trying to create an instance of TestClass but we are calling a constructor that does not exist! TestClass has no constructor that accepts one argument but the compiler complains about something totally different. If we remove the argument from the constructor call overload resolution starts working again.
Also notice how Method is called... that's right, by passing the callback argument by name, this is also necessary to reproduce the meaningless (at least on the surface) compiler error.
It is possible that the same error occurs in cases without lambdas but I didn't bother to test it further.
In a presentation(I can't recall the exact video) about C# 4.0 Anders Hejlsberg said that he resisted implementing named arguments in C# because it brings a lot of complexity into the compiler. I think we are now observing the bad side effects of that added complexity and any program complexity for that matter.
So if you find yourself fighting with a lambda error keep this in mind, it just might save you a head bang or two.
Copyright © 2017, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
Progress, Telerik, and certain product names used herein are trademarks or registered trademarks of Progress Software Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See Trademarks or appropriate markings.