New for Visual Studio 2008 - Support for anonymous methods and lambda expressions

One of my favorite new features for Code Analysis in Visual Studio 2008 is our support for analyzing anonymous methods and lambda expressions. While anonymous methods have been around in C# since Visual Studio 2005, lambda expressions are new for both C# and Visual Basic in Visual Studio 2008.

For those that are already familiar with the concept of anonymous methods (if not check out this article), lambda expressions provide a simpler, more concise syntax for writing inline methods. They also serve as the underpinnings of Linq.

Take the following code written in Visual Studio 2005 which converts a list of strings to uppercase, for example:

    internal static class StringFormatter
{
public static List<string> ToUpper(List<string> values, CultureInfo culture)
{
return values.ConvertAll(delegate(string value)
{
return value.ToUpper(culture);
});
}
}

Using the new lambda syntax, the equivalent can be written in C# and Visual Basic like so:

        internal static class StringFormatter
{
public static List<string> ToUpper(List<string> values, CultureInfo culture)
{
return values.ConvertAll(value => value.ToUpper(culture));
}
}

    Friend Module StringFormatter

Public Function ToUpper(ByVal values As List(Of String), ByVal culture As CultureInfo) As List(Of String)

Return values.ConvertAll(Function(value) value.ToUpper(culture))

End Function

End Module 

To understand how lambda expressions and anonymous methods are implemented underneath in IL (which is important for a tool like Code Analysis that runs over the binary and not the source), see the great in-depth posts by Raymond Chen for C# (Parts 1, 2, and 3) and Jared Parsons for Visual Basic (Parts 1, 2, 3, 4 and 5). Once you've read those posts, you'll understand why Code Analysis didn't get support for this for free.

What does this mean for Code Analysis users? Well, previously, in Visual Studio 2005, the engine would simply skip over these constructs and the user wouldn't find out about any violations, if any, contained within them. The good news is that we will now analyze them. The bad news is that any project making heavy use of anonymous methods is likely no longer Code Analysis clean on its upgrade to Visual Studio 2008. ;)

For a little more information on Code Analysis's support of anonymous methods, see the following topic: Anonymous Methods and Code Analysis (code formatting to be fixed for RTM).

Note: These is a bug in Beta 2 that prevents Code Analysis from analyzing lambdas/anonymous methods that access any locals or parameters outside of its own scope. This will be fixed in RTM of Visual Studio 2008.