Debugging lambda expressions

Visual Studio 2015 has added the ability for developers to debug lambda expressions. This is a fantastic addition to the features of our favorite IDE. It allows us to check the results of a lambda expression on the fly and modify the expression to test different scenarios.

Getting ready

We will create a very basic lambda expression and change it in the Watch window to produce a different value.

How to do it…

  1. Add a class called CSharpSix. Add a property to this class called FavoriteFeature:
    public class CSharpSix
    {
        public string FavoriteFeature { get; set; }
    }
  2. Next, create a List<CSharpSix> object and add a few of your favorite C# 6 features to this list:
    List<CSharpSix> FavCSharpFeatures = new List<CSharpSix>();
    CSharpSix feature1 = new CSharpSix();
    feature1.FavoriteFeature = "String Interpolation";
    FavCSharpFeatures.Add(feature1);
    
    CSharpSix feature2 = new CSharpSix();
    feature2.FavoriteFeature = "Exception Filters";
    FavCSharpFeatures.Add(feature2);
    
    CSharpSix feature3 = new CSharpSix();
    feature3.FavoriteFeature = "Nameof Expressions";
    FavCSharpFeatures.Add(feature3);
  3. Then, create an expression to return only the features starting with the "Ex" string. Here, we would obviously expect to see exception filters as a result:
    var filteredFeature = FavCSharpFeatures.Where(feature => feature.FavoriteFeature.StartsWith("Ex"));
  4. Place a breakpoint on the expression and run your application. When the code stops at the breakpoint, you can copy the lambda expression:
    How to do it…
  5. Paste the lambda expression into your Watch windows and change the string in the StartsWith method. You will see that the result has changed to the "Nameof Expressions" string:
    How to do it…

How it works…

Being able to debug lambda expressions allows us to change and debug a lambda expression easily. This is something that was not possible in previous versions of Visual Studio. It is obviously of great importance to know this tip when working with these expressions.

Another point to note is that you can do the same thing from the Immediate window in Visual Studio 2015, as well as pinned variables from the lambda expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.109.8