0

The Visual Studio 2013 debugger is behaving in an unexpected way after applying .ToString() to a StringBuilder. In the controller, I'm attempting to intercept some errors, and have adapted some code from this SO post. How to get all Errors from ASP.Net MVC modelState?

But when the debugger runs, and after a .ToString() action is applied to the StringBuilder, I'm unable to inspect the contents of the string via Watch or hovering over the string.

string theErrors = string.Empty;
if (!ModelState.IsValid)
{
    StringBuilder sb = new StringBuilder();
    foreach (ModelState modelState in ViewData.ModelState.Values)
    {
        foreach (ModelError error in modelState.Errors)
        {
            sb.AppendFormat("{0}{1}", error.ErrorMessage, Environment.NewLine);
        }
    }
    theErrors = sb.ToString();
    sb = null;
}

If I place a breakpoint after this code, and try to inspect the "theErrors" string, Visual Studio debugger displays this message.

"The name 'theErrors' does not exist in the current context."

This is unexpected behavior. Am I doing something wrong with the StringBuilder? I use StringBuilder frequently, and haven't seen this before. Thanks for your help.

Community
  • 1
  • 1
Ken Palmer
  • 2,355
  • 5
  • 37
  • 57
  • What build configuration are you using? Are you using `tblErrors` anywhere after this code? – Jason Boyd May 19 '16 at 19:15
  • Thanks Jason. Don't know if I'm following your question. I intend to use that variable later int the code. For my sanity, I replaced the StringBuilder with a string and just started concatenating to it. And *that* does capture the error. I can run with that workaround, but it's annoying StringBuilder isn't working as expected. – Ken Palmer May 19 '16 at 19:20
  • 1
    I mean is your configuration set to 'release' or 'debug'. In a 'release' build the compiler will optimize out unused variables. – Jason Boyd May 19 '16 at 19:23
  • The error isn't about the `StringBuilder`, that would be `The name "sb" does not exist in the current context`. – Eris May 19 '16 at 19:25
  • Ah, that's it! Configuration was set to release. And that had slipped my mind. Switching to Debug corrected this. Thanks Jason. Please post that as an answer so I can award that. – Ken Palmer May 19 '16 at 19:28

1 Answers1

1

Your build configuration is set to 'release'.

enter image description here

The 'Optimize Code' option is enabled by default in the 'Release' configuration.

enter image description here

Code optimization will optimize out any unused variables. Changing your build configuration to 'Debug' will stop this.

Jason Boyd
  • 6,839
  • 4
  • 29
  • 47