Value Debugging

Introduction

In the previous lessons, we were introduced to debugging and some of the tools that Microsoft Visual Studio provides. The intent was to be introduced to some means of identifying the variables and monitoring their values.

Practical LearningPractical Learning: Introducing Errors

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PayrollEvaluation2
  3. Change the contents of the Program.cs document as follows:
    using static System.Console;
    
    int     employeeId   = default;
    long    number       = 0L;
    string? firstName    = null;
    string? lastName     = null;
    double  hourlySalary = 0.00;
    double  timeWorked   = 0;
    double  netPay       = hourlySalary * timeWorked;
    
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    number);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");
  4. To start debugging, in the Solution Explorer, right-click the StraightLineMethod2 project -> Debug -> Step Into New Instance

Observing Variable Changes

One of the most valuable techniques that Microsoft Visual Studio offers is to observe the value of a variable directly in the Code Editor as soon as that value is changed. You have many options. The primary option is to position the mouse at any time on any part that the variable is used and observe its value.

Practical LearningPractical Learning: Observing Variable Changes

  1. In the Code Editor where the variables are declared, position the mouse on top of the hourlySalary variable and notice its value:

    Debugging - The Value of a Variable

  2. On Line 24, position the mouse on top of the hourlySalary variable and notice its value:

    Debugging - The Value of a Variable

    In the same way, notice the values of the variables in the Locals window:

    The Locals Window - Value

    And notice the values of the variables in the Autos window:

    The Locals Window - Value

  3. Still in the Code Editor where the values of the variables are displayed with WriteLine(), position the mouse on top of each variable and notice its value:

    Debugging - The Value of a Variable

    Debugging - The Value of a Variable

  4. Change the document as follows:
    using static System.Console;
    
    int     employeeId     = default;
    long    employeeNumber = 0L;
    string? firstName      = null;
    string? lastName       = null;
    double  hourlySalary   = 0.00;
    double  timeWorked     = 0;
    double  netPay         = hourlySalary * timeWorked;
    
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    employeeNumber);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");
    
    employeeId             = 1;
    employeeNumber         = 597_485;
    firstName              = "Lynda";
    lastName               = "Elroy";
    hourlySalary           = 25.73;
    timeWorked             = 36.50;
    netPay                 = hourlySalary * timeWorked;
     
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    employeeNumber);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");");
  5. On the Debug toolbar, click the Step Into Step Into button a few times (21 times) until focus is on Line 26; that is, after Line 25 has been executed but before Line 26 executes:

    Debugging - The Value of a Variable

  6. In the Code Editor where the variables are declared, position the mouse on top of the employeeNumber variable and notice its value:

    Debugging - The Value of a Variable

  7. On Line 16, position the mouse on top of the employeeNumber variable and notice its value:

    Debugging - The Value of a Variable

  8. On Line 37, position the mouse on top of the employeeNumber variable and notice its value
  9. On the Debug toolbar, keep clicking the Step Into Step Into button. Every time you click it, position the mouse on every variable to see its current value. Also observe the variables and their values in both the Locals and the Autos windows:
    Payroll Evaluation
    ===========================
    Employee Record
    ---------------------------
    Employee Id:    0
    Employee #:     0
    First Name:
    Last Name:
    Hourly Salary:  0
    Time Worked:    0
    Net Pay:        0
    ===========================
    Payroll Evaluation
    ===========================
    Employee Record
    ---------------------------
    Employee Id:    1
    Employee #:     597485
    First Name:     Lynda
    Last Name:      Elroy
    Hourly Salary:  25.73
    Time Worked:    36.5
    Net Pay:        939.145
    ===========================
    
    Press any key to close this window . . .
  10. In the DOS window, press E to close that window and return to your programming environment
  11. Change the document as follows:
    using static System.Console;
    
    int     employeeId     = 2;
    long    employeeNumber = 249_358;
    string? firstName      = "Robert";
    string? lastName       = "Denison";
    double  hourlySalary   = 30.08;
    double  timeWorked     = 38.50;
    double  netPay         = hourlySalary * timeWorked;
    
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    employeeNumber);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");
    
    employeeId             = 3;
    employeeNumber         = 794_837;
    firstName              = "Rachel";
    lastName               = "Nielsen";
    hourlySalary           = 22.88;
    timeWorked             = 42.50;
     
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    employeeNumber);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");
  12. To start debugging, in the Solution Explorer, right-click the name of the project -> Debug -> Step Into New Instance
  13. Throughout the Code Editor, position the mouse on top of each variable and notice its value. Also observe the variables and their values in both the Locals and the Autos windows
  14. To continue debugging, keep pressing F11. After each press, position the mouse on top of each variable in the upper and the lower sections of the Code Editor to see the current value of the variable. Also check the values in the Locals and the Autos windows.
    If necessary (that is, at any time, to stop debugging), on the main menu of Microsoft Visual Studio, click Debug -> Stop Debugging

Running to the Cursor

Imagine that, when your code is executing, there is some behavior that is a concern to you about a certain line of code. Instead of debugging the whole document, you can ask the debugger to jump straight to that particular line. To assist you with this operation, Microsoft Visual Studio provides the Run To Cursor feature. It is available from the context-sensitive menu.

Practical LearningPractical Learning: Running to the Cursor

  1. To restart debugging, in the Code Editor, right-click anywhere on Line 18 (last Name) and click Run To Cursor
  2. Throughout the Code Editor, position the mouse on top of each variable and notice its value. Also observe the variables and their values in both the Locals and the Autos windows
  3. To continue debugging, in the Code Editor, right-click anywhere on Line 36 (employeeNumber) and click Run To Cursor
  4. Throughout the Code Editor, position the mouse on top of each variable and notice its value. Also observe the variables and their values in both the Locals and the Autos windows
  5. On the Debug toolbar, click the Step Into button Step Into a few times until all values display in the DOS window
  6. Start a new Console App. Name it WattsALoan1
  7. Change the Program.cs document as follows:
    using static System.Console;
    
    double principal;
    double interestRate;
    double period;
    double interestAmount;
    double futureValue;
    
    Title = "Watts' A Loan?";
    
    WriteLine("This application allows you to evaluate a loan");
    WriteLine("To proceed, enter the following values");
    WriteLine("=---------------------------------------------=");
    
    Write("Enter the principal:        ");
    principal      = double.Parse(ReadLine()!);
    Write("Enter the interest rate:    ");
    interestRate   = double.Parse(ReadLine()!) / 100;
    Write("Enter the number of months: ");
    period         = double.Parse(ReadLine()!) / 12;
    
    interestAmount = principal * interestRate * period;
    futureValue    = principal + interestAmount;
    
    WriteLine("===============================================");
    WriteLine("Loan Summary");
    WriteLine("=---------------------------------------------=");
    WriteLine("Principal:                  {0:F}", principal);
    WriteLine("Interest Rate:              {0:P}", interestRate);
    WriteLine("Period For:                 {0} months", period * 12);
    WriteLine("Interest Amount:            {0:F}", interestAmount);
    WriteLine("Future Value:               {0:F}", futureValue);
    WriteLine("==============================================");

Visualizing a Variable

Introduction

In previous sections and lessons, we saw various ways to monitor the variables and their values. Other features of Microsoft Visual Studio are available. For example, after starting a debugging session, position your mouse on a variable. From there, other options to debug would be offered to you.

Debugging and Data Entry

So far, in our introduction to debugging, we provided the values to monitor on variables. In most of your programs, the users will provide the values your program needs to use. As the users are doing that, you may want to observe the changes, be able to identify the problems and then fix them.

Practical LearningPractical Learning: Debugging while Entering Data

  1. While the Code Editor is displaying the code you typed, on the main menu, click Debug -> Step Into.
    Move the windows to make sure you can see the Code Editor, the Locals window, and the DOS window. Here is an example:

    Debugging

  2. Notice the yellow arrow button on the left of a line of code.
    Notice that the Locals window displays the variables.
    Notice that the DOS window is not displaying anything and its title bar is showing the path of the project
  3. To continue debugging, on the Debug toolbar, click the Step Into button Step Into
  4. To continue debugging, keep pressing F11 (4 times) until the focus moves to the DOS window. You will know when the lines in the Locals window are disabled and the caret is blinking in the DOS window while requesting a value
  5. When asked to enter a value for the principal, type 6500 and press Enter
  6. Notice that the focus moves back to the Code Editor.
    Notice that the value of the principal has changed in the Locals grid:

    Debugging

    Press F11
  7. Press F11 again
  8. When the caret starts blinking in the DOS window as you are asked to provide the interest rate, type 12.225 and press Enter.
    The focus moves back to the Code Editor.
    Notice that the value of the interestRate variable in the Locals window has changed

    Debugging

  9. Press F11
  10. Press F11 again
  11. The focus moves to the DOS window. When the number of months is requested, type 48 and press Enter.
    The focus moves back to the Code Editor.
    Notice that the value of the period variable in the Locals window has been changed

    Debugging

  12. Press F11

    Debugging

  13. Press F11

    Debugging

  14. Press F11

    Debugging

  15. Continue pressing F11 until the DOS window displays a summary of the calculations:
    This application allows you to evaluate a loan
    To proceed, enter the following values
    =---------------------------------------------=
    Enter the principal:        6500
    Enter the interest rate:    12.625
    Enter the number of months: 48
    ===============================================
    Loan Summary
    =---------------------------------------------=
    Principal:                  6500.00
    Interest Rate:              12.63%
    Period For:                 48 months
    Interest Amount:            3282.50
    Future Value:               9782.50
    ==============================================
    
    Press any key to close this window . . .
  16. Press Enter to get back to your programming environment
  17. Press F11 to end
  18. Re-open the PayrollPreparation2 project that was created in the begining
  19. Change the document as follows:
    using static System.Console;
    
    Title = "Payroll Evaluation";
    
    int     employeeId   = 4;
    long    number       = 938_074;
    string? firstName    = "Anthony";
    string? lastName     = "Jenkins";
    double  hourlySalary = 0.00;
    double  timeWorked   = 0;
    double  netPay       = hourlySalary * timeWorked;
    
    WriteLine("Payroll Evaluation");
    WriteLine("===========================");
    WriteLine("Employee Record");
    WriteLine("---------------------------");
    WriteLine("Employee Id:\t{0}",   employeeId);
    WriteLine("Employee #:\t{0}",    number);
    WriteLine("First Name:\t{0}",    firstName);
    WriteLine("Last Name:\t{0}",     lastName);
    WriteLine("Hourly Salary:\t{0}", hourlySalary);
    WriteLine("Time Worked:\t{0}",   timeWorked);
    WriteLine("Net Pay:\t{0}",       netPay);
    WriteLine("===========================");
  20. To start debugging, in the Solution Explorer, right-click the name of the project -> Debug -> Step Into New Instance.
    Notice the values of the variables in the Locals window.
    In the Code Editor, position the mouse on the hourlySalary variable to see its value
  21. Click the Autos tab and notice that its window is showing only one variable
  22. Click the Locals tab to access its window
  23. On the Debug toolbar, keep clicking the Step Into Step Into button.
    In the Locals and the Autos windows, observe the changing values of the variables.
    Observe the changes in the DOS window.
    Keep clicking the Step Into Step Into button (19 times) until all values display in the DOS window:
    Payroll Evaluation
    ===========================
    Employee Record
    ---------------------------
    Employee Id:    4
    Employee #:     938074
    First Name:     Anthony
    Last Name:      Jenkins
    Hourly Salary:  0
    Time Worked:    0
    Net Pay:        0
    ===========================
    
    Press any key to close this window . . .
  24. To start debugging again, in the Solution Explorer, right-click the name of the project -> Debug -> Step Into New Instance
  25. On the Debug toolbar, keep clicking the Step Into Step Into button (8 times) until the focus is on the WriteLine("Payroll Evaluation"); line:

    Debugging

Testing the Values in the Debugging Windows

We have seen that the Locals window is there to assist us in observing the values that are changing in the Code Editor. Another way to use the Locals window is to test the values directly in that window. This means that you can manually change a value of a variable in the Locals window and see what happens. Remember that the Autos window also is used to show the variables and their changing values.

Practical LearningPractical Learning: Testing the Values in the Locals Window

  1. In the Locals window, double-click the 0.00 value of hourlySalary to edit it
  2. Type 22.87 and press Enter
  3. In the Code Editor, position the mouse on the hourlySalary variable to see its value:

    Debugging


    In the same way, position your mouse on the other hourlySalary intances
  4. In the Code Editor, position the mouse on the timeWorked variables to see their values
  5. In the Code Editor, position the mouse on the netPay variables to see their values
  6. In the Locals window, double-click the 0.00 value of timeWorked to edit it
  7. Type 39.50 and press Enter
  8. In the Code Editor, position the mouse on various parts where the timeWorked variable appears
  9. In the Code Editor, position the mouse on the weeklySalary variable to see its value.
    Position your mouse wherever the netPay variable appears to see its value
  10. On the Debug toolbar, keep clicking the Step Into Step Into button.Observe the variables and their values in the Locals window.Observe the changes in the DOS window:

    Debugging

    Debugging

    Debugging

    Keep clicking the Step Into Step Into button until the DOS window has displayed all values
  11. Re-open the WattsALoan2 project that was previously used:
    using static System.Console;
    
    double principal;
    double interestRate;
    double period;
    double interestAmount;
    double futureValue;
    
    Title = "Watts' A Loan?";
    
    WriteLine("This application allows you to evaluate a loan");
    WriteLine("To proceed, enter the following values");
    WriteLine("=---------------------------------------------=");
    
    Write("Enter the principal:        ");
    principal      = double.Parse(ReadLine()!);
    Write("Enter the interest rate:    ");
    interestRate   = double.Parse(ReadLine()!) / 100;
    Write("Enter the number of months: ");
    period         = double.Parse(ReadLine()!) / 12;
    
    interestAmount = principal * interestRate * period;
    futureValue    = principal + interestAmount;
    
    WriteLine("===============================================");
    WriteLine("Loan Summary");
    WriteLine("=---------------------------------------------=");
    WriteLine("Principal:                  {0:F}", principal);
    WriteLine("Interest Rate:              {0:P}", interestRate);
    WriteLine("Period For:                 {0} months", period * 12);
    WriteLine("Interest Amount:            {0:F}", interestAmount);
    WriteLine("Future Value:               {0:F}", futureValue);
    WriteLine("==============================================");
  12. To start debugging, on the main menu of Microsoft Visual Studio, click Debug -> Step Into
  13. On the Debug toolbar, keep clicking the Step Into Step Into button until the caret is blinking in the DOS window

Exceptional Debugging

Introduction

As you should know already, an exception is a type of eror that occurs when your program has started running or executing. It is usually not a syntax or a logic error. As a result, that type of error may not be obvious while you are writing your code in the Code Editor. It is usually an error that would either prevent your program from running or would produce unreliable results.

Debugging is an operation that allows you to identify some exceptions that your applications can throw and add code that would deal with them.

Practical LearningPractical Learning: Testing the Values in the Locals Window

  1. In the DOS window where the value of the principal is requested, type $22850 and press Enter.
    Notice that the application throws a FormatException exception represented by a window:

    Debugging - Throwing an Exception

  2. To stop the execution, on the Debug toolbar, click the Step Out button Step Out
  3. To start debugging again, on the Debug toolbar, keep clicking the Step Into Step Into button until the caret is blinking in the DOS window
  4. In the DOS window where the value of the principal is requested, type 22850 and press Enter
  5. To continue debugging, on the Debug toolbar, clicking the Step Into Step Into button twice until the caret is blinking in the DOS window
  6. In the DOS window where the value of the interest rate is requested, type 8.225% and press Enter.
    Notice that the application throws another FormatException exception represented by a window:

    Debugging - Throwing an Exception

  7. To stop debugging, on the main menu of Microsoft Visual Studio, click Debug -> Step Out

Adding Exceptions

As you may know already, exception handling is the ability to address issues related to types of errors in your application. To do that, you should write appropriate code that deals with known exceptions.

Practical LearningPractical Learning: Testing the Values in the Locals Window

  1. Change the document as follows:
    using static System.Console;
    
    double futureValue;
    double interestAmount;
    double period       = default;
    double principal    = default;
    double interestRate = default;
    
    Title = "Watts' A Loan?";
    
    WriteLine("This application allows you to evaluate a loan");
    WriteLine("To proceed, enter the following values");
    WriteLine("=---------------------------------------------=");
    
    try
    {
        Write("Enter the principal:        ");
        principal = double.Parse(ReadLine()!);
    }
    catch (FormatException exc)
    {
        WriteLine("The value you typed for the principal is not valid.");
        WriteLine("The error produced is: " + exc.Message);
    }
    
    try
    {
        Write("Enter the interest rate:    ");
        interestRate   = double.Parse(ReadLine()!) / 100;
    }
    catch (FormatException exc)
    {
        WriteLine("The value you typed for the interest rate is not appropriate.");
        WriteLine("The error is: " + exc.Message);
    }
    
    try
    {
        Write("Enter the number of months: ");
        period         = double.Parse(ReadLine()!) / 12;
    }
    catch (FormatException exc)
    {
        WriteLine("The number of months you typed cannot be accepted.\n" +
                  "The application produced the following error: " + exc.Message);
    }
    
    interestAmount = principal * interestRate * period;
    futureValue    = principal + interestAmount;
    
    WriteLine("===============================================");
    WriteLine("Loan Summary");
    WriteLine("=---------------------------------------------=");
    WriteLine("Principal:                  {0:F}", principal);
    WriteLine("Interest Rate:              {0:P}", interestRate);
    WriteLine("Period For:                 {0} months", period * 12);
    WriteLine("Interest Amount:            {0:F}", interestAmount);
    WriteLine("Future Value:               {0:F}", futureValue);
    WriteLine("==============================================");
  2. To start debugging, on the main menu of Microsoft Visual Studio, click Debug -> Step Into
  3. On the Debug toolbar, keep clicking the Step Into Step Into button until the caret is blinking in the DOS window
  4. In the DOS window where the value of the principal is requested, type $22850 and press Enter.
    Notice that the application throws a FormatException exception represented by a window:

    Debugging - Throwing an Exception

  5. In the Exception Caught window, click the Continue button
  6. In the DOS window, as the interest rate is requested, type 8.225% and press Enter
  7. Still in the DOS window, as the number of months is requested, type 48 months and press Enter
    This application allows you to evaluate a loan
    To proceed, enter the following values
    =---------------------------------------------=
    Enter the principal:        $22850
    The value you typed for the principal is not valid.
    The error produced is: The input string '$22850' was not in a correct format.
    Enter the interest rate:    8.225%
    The value you typed for the interest rate is not appropriate.
    The error is: The input string '8.225%' was not in a correct format.
    Enter the number of months: 48 months
    The number of months you typed cannot be accepted.
    The application produced the following error: The input string '48 months' was not in a correct format.
    ===============================================
    Loan Summary
    =---------------------------------------------=
    Principal:                  0.00
    Interest Rate:              0.00%
    Period For:                 0 months
    Interest Amount:            0.00
    Future Value:               0.00
    ==============================================
    
    Press any key to close this window . . .
  8. To start debugging again, on the main menu of Microsoft Visual Studio, click Debug -> Step Into
  9. Close your programming environment

Previous Copyright © 2010-2026, FunctionX Wednesday 12 November 2025, 14:05 Next