September 05, 2012

My Favorite Visual Studio 2012 Breaking Change

It is not very often that you see the words "favorite" and "breaking change" within the same sentence.  However, I will say with VS 2012 and .NET 4.5 there happens to be one that I thought I would call special attention to here on my blog as I've talked about the old behavior many times in talks throughout the past few years.

The specific breaking change that I'm so happy is done is with regards to Lambdas and how they are handled when used inside of a foreach loop.  Consider the following code to demonstrate the issue.  (Credits to Microsoft for the sample code.)

static void Main()
{
    var lines = new List<IEnumerable<string>>(); 
    int[] numbers = { 1, 2, 3 };
    char[] letters = { 'a', 'b', 'c' };

    foreach (var number in numbers)
    {
        var line = from letter in letters
                   select number.ToString() + letter;

        lines.Add(line);
    }

    foreach (var line in lines)
    {
        foreach (var entry in line)
            Console.Write(entry + " ");
        Console.WriteLine();
    }
}

Those of us that have used LINQ in previous versions of .NET would instantly know that we would get incorrect results with the above code.  Rather than getting three lines of text starting with 1a 1b 1c then 2a etc.  We would get three lines with 3a 3b 3c.  The fix for this was very easy, simply changing the first foreach loop to something like this would solve the issue.

foreach (var number in numbers)
{
    var item = number;
    var line = from letter in letters
               select item.ToString() + letter;

    lines.Add(line);
}

Well the breaking change makes this practice no longer needed! Tools like ReSharper were great in warning developers of this potential issue, but I know a number of people that were bit by this issue.

If you are interested in learning more about breaking changes in .NET 4.5 you can read up on them via the following articles. Visual C# Breaking Changes Visual Basic Breaking Changes

tags: C#, .NET 4.5
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.