Friday, September 4, 2015

False Blame on Caller of Uncompilable Lambdas in Visual Studio 2015

Today while doing some work in Visual Studio 2015, I noticed some odd behavior involving multiline lambdas passed to functions. My code includes invocations of Task.Factory.StartNew with a moderately complex parameterless, void-returning delegate - an Action - passed to it like so:

Task.Factory.StartNew(Sub()
                          ' Do some stuff
                          ' And some things
                      End Sub)

I was doing some refactoring that involved removing a variable from one function since the capability that required it was being moved somewhere else. After I deleted the declaration line, I noticed that Visual Studio put a red squiggly underline on StartNew, indicating a compilation error. Mousing over the underlined text informed me that the type of the parameter could not be inferred.

That was very strange, since the type of a Sub() lambda is completely unambiguous - it's always just Action with no type parameters. I set it aside for a moment and finished my refactoring of the lambda. Once all references to the nonexistent variable were removed, the error went away.

Assigning the large uncompilable lambda to a variable and then passing the variable to the StartNew function worked as expected; uses of the variable inside the lambda received squiggles. It appears that the Visual Studio 2015 compiler incorrectly lays the blame for all errors inside a lambda-as-an-argument on the calling function as type confusion.

No comments:

Post a Comment