Wednesday, July 9, 2014

Watch a variable when debugging in Visual Studio 2013.

 
 

This is especially helpful when a variable is changing at every step inside a loop, for example in code like so...

using System.Collections.Generic;
using System.Web.Mvc;
namespace Vowels.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         List<string> vowels = new List<string>() { "a", "e", "i", "o", "u", "y" };
         foreach (string vowel in vowels)
         {
            var dressUp = vowel;
            if (vowel != "y")
            {
               dressUp = vowel + ", ";
            } else {
               dressUp = "and sometimes " + vowel;
            }
            ViewBag.Title += dressUp;
         }
         return View();
      }
   }
}

 
 

...with a breakpoint set downstream (but not too far downstream) of the variable you wish to watch, right-click on the variable, while stopped at the breakpoint in debugging, and pick "Add Watch" which will give you the value of the variable in a separate pane which will be kept up to date as changes occur.

No comments:

Post a Comment