Debugging Preparation

Introduction

A logic error is called a bug. Debugging is the process of examining code to look for bugs or to identify problems. Debugging is the ability to monitor the behavior of a variable, an object (from a class, an interface, a record, or a structure), or its members throughout a program. Microsoft Visual Studio provides many tools, accessories, and features to perform debugging operations.

Probably the most fundamental way of examining code is to read every word and every line, with your eyes, using your experience as a programmer. This can work for short code written in one file and in one class. If the code to examine covers many pages or many files, it could be awful and tiresome to examine code with your eyes line by line. Fortunately, to assist you with this operation, Microsoft Visual Studio provides various tools and windows you use, one window, or a combination of objects.

Practical LearningPractical Learning: Introducing Errors

  1. Start Microsoft Visual Studio
  2. Create a new Console App named LoanEvaluation1
  3. Change the contents of the Program.cs document as follows:
    using static System.Console;
    
    int id = 1;
    long number = 597_485;
    string? firstName = "Lynda";
    string? lastName = "Elroy";
    double hSal = 25.73;
    double time = 36.50;
    
    WriteLine("Employee Record");
    WriteLine("------------------------");
    WriteLine("Employee Id:\t{0}", id);
    WriteLine("Employee #:\t{0}", number);
    WriteLine("First Name:\t{0}", firstName);
    WriteLine("Last Name:\t{0}", lastName);
    WriteLine("Hourly Salary:\t{0}", hSal);
    WriteLine("Time Worked:\t{0}", time);
    WriteLine("Weekly Salary:\t{0}", hSal * time);
    WriteLine("===========================");

A Debugger

To assist you with debugging, Microsoft Visual Studio includes an application named a debugger. As its name suggests, that application is used to debug your code. The code or application that you are debugging is called the debuggee. When you are debugging your code as we will see, the debugger gets "attached" to the compiler (or other applications, such as the lexer) that examines and validates your code.

The Debug Toolbar

Introduction

Besides its main menu, one of the tools Microsoft Visual Studio provides for debugging is a toolbar named Debug. It is equipped with various debugging buttons:

The Debug Toolbar

Using the Debug Toolbar

Like its name suggests, the purpose of the Debug toolbar is to assist you with debugging operations. For that reason, the Debug toolbar is equipped with various buttons.

Stepping Into Code

As you may know already, one of the ways you debug an application is to examine code one statement at a time. To perform this operatinn using the Debug toolbar, it is equipped with a Step Into button Step Into. You can click that button to perform the related operation.

Practical LearningPractical Learning: Stepping Into Code

  1. Click anywhere in the Program.cs document to make sure it has focus.
    On the main menu, click Debug -> Step Into.
    Notice the black DOS window that comes up. If you are using more than one monitor, position that black window in another monitor
  2. On the Debug toolbar, click the Step Into Step Into button
  3. Keep clicking the Step Into Step Into button.
    Observe as the focus keeps moving from one line to another in the Code Editor.
    Keep observing the changes in the DOS window.
    Keep doing that until the last line of code:
    Employee Record
    ------------------------
    Employee Id:    1
    Employee #:     597485
    First Name:     Lynda
    Last Name:      Elroy
    Hourly Salary:  25.73
    Time Worked:    36.5
    Weekly Salary:  939.145
    ===========================
    
    To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
    Press any key to close this window . . .

Stopping a Debugging Session

You can use the Debug toolbar to end a debugging operation. To make this possible, the Debug toolbar is equipped with a Stop Debugging button Stop Debugging

Stepping Out of Code

We saw that the Step Into operation allows you to examine your code one line at a time. If you keep performing that operation, the effects or results of some lines would become predictable. If that becomes the case, you may want to start the examinations of early lines but then you may want to skeep all the rest of the lines to get to the last line. To let you do this, Microsoft Visual Studio provides an operation named Step Out. To perform the Step Out operation, first start a debugging operation. Then:

Practical LearningPractical Learning: Stepping Out of Code

  1. To start debugging, on the main menu, click Debug -> Step Into.
    Notice that the test starts on the first line
  2. On the Debug toolbar, click the Step Into button Step Into 8 times
  3. On the Debug toolbar, click the Step Out button Step Out.
    Notice that the DOS window displays all results
  4. In the DOS window, press any key to close it
  5. To start debugging again, in the Solution Explorer, right-click the name of the project -> Debug -> Step Into New Instance.
    Notice that the test starts on the first line
  6. On the Debug toolbar, click the Step Into button Step Into 8 times
  7. On the Debug toolbar, click the Step Out button Step Out
  8. Change the document as follows:
    using static System.Console;
    
    double  machineCost;
    double  salvageValue;
    int     estimatedLife;
    long    estimationNumber;
    string? machineIdentification;
    
    Title = "Depreciation: Straight-Line Method";
    
    WriteLine("Enter the values for the machine depreciation");
    WriteLine("=============================================");
    Write("Machine Make and Model:      ");
    machineIdentification = ReadLine();
    Write("Estimation Number:           ");
    estimationNumber = int.Parse(ReadLine()!);
    Write("Machine Cost:                ");
    machineCost   = double.Parse(ReadLine()!);
    Write("Salvage Value:               ");
    salvageValue  = double.Parse(ReadLine()!);
    Write("Estimated Life (in Years):   ");
    estimatedLife = int.Parse(ReadLine()!);
    
    double depreciatiableAmount = machineCost - salvageValue;
    double depreciationRate     = 100 / estimatedLife;
    double yearlyDepreciation   = depreciatiableAmount / estimatedLife;
    
    WriteLine("=============================================");
    WriteLine("Estimation Number:           {0}", estimationNumber);
    WriteLine("Machine Identification:      {0}", machineIdentification);
    WriteLine("Depreciation - Straight-Line Method");
    WriteLine("---------------------------------------------");
    WriteLine("Machine Cost:                {0}", machineCost);
    WriteLine("Salvage Value:               {0}", salvageValue);
    WriteLine("Estimate Life:               {0} Years", estimatedLife);
    WriteLine("Depreciation Rate:           {0}%", depreciationRate);
    WriteLine("---------------------------------------------");
    WriteLine("Depreciable Amount:          {0}", depreciatiableAmount);
    WriteLine("Yearly Depreciation:         {0:N}", yearlyDepreciation);
    WriteLine("=============================================");

The Autos Window

Introduction

Debugging allows you to identify and fix problems. One way to do that is to monitor the values that a certain variable or object is holding. This is because some time to time, the value of a variable changes. As a result, debugging allows you to monitor the changing values of a variable. There are various ways you can get that information. To assist you in monitoring the values of a variable, Microsoft Visual Studio provides a window named Autos.

As you should be aware already, a C# project can have one or more files, and each file can have 0 or more variables. When you start debugging, the focus is on a certain area of your code, and that area can have 0 or more variables. When you are debugging, in the area where the debugger is acting, if that area has one or more variables, the Autos window shows (only) the variable(s) in that immediate area.

Getting the Autos Window

Normally, when you start debugging, the Autos window shows automatically. During debugging, if the Autos window is hidden, to display it:

The Autos window shows the values of variables as the program is progressing in its execution. Because code can have more than one variable, the Autos window displays a table (or grid) with many rows. The table is organized in columns. Each column displays a title for its role.

Practical LearningPractical Learning: Introducing the Autos Window

  1. On the main menu, click Debug -> Step Into.
    Move the DOS window so you can see both your code and that window
  2. In the bottom section of Microsoft Visual Studio, click the Autos tab to access the Autos window

The Name of an Item

The Autos window starts with a column titled Name. If the focus is on a function/method call, the colum displays not only the names of variables but also other items.

Practical LearningPractical Learning: Checking the Names o Variables

  1. To keep moving in the code, on the main menu of Microsoft Visual Studio, click Debug -> Step Into. Do that a few times (five times) until the Step Into menu item and button are disabled (the DOS window will receive focus)
  2. When the Machine Make and Model is requested, type Celesta DTS-6628 and press Enter.
    Observe the record in the Name column of the Autos window:

    The Autos Window

The Value of a Variable

The Value columns shows the value of a variable. As debugging progresses, the Autos window displays the name of the variable that is currently accessed. The current value of that variable is displayed in the Value column.

Practical LearningPractical Learning: Showing the Value of a Variable

The Type of a Variable

The Type column shows the data type of the variable.

Practical LearningPractical Learning: Checking the Types of Variables

  1. In the Autos window, observe the value in the Type column:

    The Autos Window - Value

    On the Debug toolbar, click the Step Into button Step Into two times to get the caret to blink on the Estimated Number line in the DOS window
  2. When the Estimated Number is requested, type 294759 and press Enter.
    Observe the values in the Name, the Value, and the Type columns in the Autos window:

    The Autos Window - The Types of Variables

  3. On the Debug toolbar, click the Step Into button Step Into twice
  4. When the Machine Cost is requested, type 6525.85 and press Enter.
    Observe the values in the Name, the Value, and the Type columns in the Autos window
  5. On the Debug toolbar, click the Step Into button Step Into twice
  6. When the Salvage Value is requested, type 555.55 and press Enter
  7. On the Debug toolbar, click the Step Into button Step Into twice
  8. When the Estimated Life (in Years) is requested, type 5 and press Enter.
    Observe the values in the Name, the Value, and the Type columns in the Autos window:

    The Autos Window - The Types of Variables

    Enter the values for the machine depreciation
    =============================================
    Machine Make and Model:      Celesta DTS-6628
    Estimation Number:           294759
    Machine Cost:                6525.85
    Salvage Value:               555.55
    Estimated Life (in Years):   5
    =============================================
    Estimation Number:           294759
    Machine Identification:      Celesta DTS-6628
    Depreciation - Straight-Line Method
    ---------------------------------------------
    Machine Cost:                6525.85
    Salvage Value:               555.55
    Estimate Life:               5 Years
    Depreciation Rate:           20%
    ---------------------------------------------
    Depreciable Amount:          5970.3
    Yearly Depreciation:         1,194.06
    =============================================
    
    Press any key to close this window . . .

The Locals Window

Introduction

As mentioned already, a C# project can have one or many files, and each file can have 0 or more variables. We saw that the Autos window shows only the variables in the proximity of the debugger's focus. Sometimes, there are variables in another section or other sections of a document.

To let you get a list of all the variables involved in the debugging scope, for example if you are working on the primary document of a C# project (remember that that document may or may not use any explicit function), to get a list of all the variables in that document, Microsoft Visual Studio provides a window named Locals.

Getting the Locals Window

When you start debugging, the Locals window shows automatically, usually in the bottom-left section of Microsoft Visual Studio. During debugging, if the Locals window is not displaying, to display it:

As its name indicates, the Locals window shows the values of local variables as they are changed. Like the Autos window, the Locals window displays a table (with columns and rows) of the variables that are being monitored.

The Name of a Variable

The Name column shows the name of each variable declared in the function or the section that is being debugged.

Locals

Practical LearningPractical Learning: Introducing the Locals Window

  1. On the main menu, click Debug -> Step Into.
    Move the DOS window so you can see both your code and that window.
    On the main menu of Microsoft Visual Studio, click Debug -> Windows -> Locals:

    The Locals Window - Value

  2. On the Debug toolbar, click the Step Into button Step Into 5 times until the caret is blinking on the Machine Make and Model line in the DOS window

The Value of a Variable

The Value columns shows the value of each variable. When debugging starts, each variable shows its default or initial value.

The Locals Window - The Value Column

As debugging progresses, when a variable acquires a new value, the Locals window updates it in the Value column. In some cases, instead of the debugger changing the value, you can manually select and change it in the Locals window and press Enter.

Practical LearningPractical Learning: Checking the Names of Variables

The Type of a Variable

The Type column shows the data type of the variable.

Practical LearningPractical Learning: Checking the Types of Variables

  1. Observe the data types in the Type column of the Locals window:

    The Autos Window

  2. On the Debug toolbar, click the Step Into button Step Into twice until the caret is blinking on the Estimation Number
  3. For the Estimation Number, type 847381 and press Enter.
    Notice the records in the Locals window:

    The Locals Window - Value

  4. On the Debug toolbar, click the Step Into button Step Into twice
  5. For the Machine Cost, type 12725 and press Enter
  6. On the Debug toolbar, click the Step Into button Step Into twice until the caret is blinking on the Salvage Value
  7. For the Salvage Value, type 845 and press Enter
  8. On the Debug toolbar, click the Step Into button Step Into twice until the caret is blinking on the Estimated Life (in Years)
  9. For the Estimated Life (in Years), type 8 and press Enter.
    Notice the records in the Locals window:

    The Locals Window - Value

  10. On the Debug toolbar, keep clicking the Step Into button Step Into and observe the rows in the DOS, the Locals, and the Autos windows:

    The Locals Window - Value

    The Locals Window - Value

  11. Change the Program.cs document as follows:
    using static System.Console;
    
    int     employeeId     = 2;
    long    employeeNumber = 283_575;
    string? firstName      = "James";
    string? lastName       = "Wiley";
    double  hourlySalary   = 31.63;
    double  timeWorked     = 42.50;
    
    double netPay = hourlySalary * timeWorked;
    
    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("Weekly Salary:\t{0}", netPay);
    WriteLine("===========================");
  12. To start debugging, on the main menu, click Debug -> Step Into.
    Move the DOS window so you can see both Microsoft Visual Studio and that DOS window.
    If the Immediate window is not available, on the main menu of Microsoft Visual Studio, click Debug -> Windows -> Immediate

The Watch Window

Introduction

Imagine you have a variable that is accessed in various parts of your code. One way you can test the behavior of that variable is to test its value as it circumstancially changes time after time. The Watch window is an object that allows you to monitor the values that a variable (or many variables) holds (or have) in various parts of the code.

Getting the Watch Window

To get the Watch window, start debugging your application (Debug -> Start Debugging or Debug -> Step Into). The Watch window would appear, usually next to the Locals window. The Watch window appears as a table with three columns. Their roles will be obvious to you once the window contains something.

Creating a Watch

Before using the services of a Watch window, you must create one or more entries, which are referred to as watches. Before creating a watch, you must start stepping into your code, which is done by clicking Debug -> Step Into or by pressing F11.

To create a watch, after starting a Step Into operation, on the main menu of Microsoft Visual Studio, click Debug -> Window -> Watch -> Watch 1. As an alternative, to create a watch, after starting a Step Into operation, on the mainthen click Debug -> QuickWatch... A window would display. Here is an example:

Quick Watch

The window is equipped with a combo box labeld Expression.

Using a Watch

The Watch window is equipped with a combo box labeld Expression. To start using a Watch window, in the Expression combo box, type the name of the variable you want to watch. You can also type an expression such as a value added to a variable. Here is an example:

Quick Watch

If you want to submit the entry, click the Add Watch button.

After creating the desired entries in the Watch window, continue debugging. You will see the values being automatically updated in the Value column of the Watch window.

If you don't need a certain entry in the Watch window, you can remove it, or you can delete all entries in the window. To remove an entry, right-click it and click Delete Watch. To remove all entries, right-click anywhere in the Watch window and click Clear All.

Practical LearningPractical Learning: Using the Watch Window

  1. If the Watch window is not displaying, on the main menu, click Debug -> Windows -> Watch -> Watch 1.
    Just in case, right-click inside the Watch window and click Clear All
  2. In the Watch window, double-click under Name, type timeWorked * 1.50 and press Enter (this will be used to evaluate overtime)
  3. Still in the Watch window, click under timeWorked * 1.50, type hourlySalary + 0.55 and press Enter
  4. Click under hourlySalary + 0.55, type timeWorked * hourlySalary and press the down arrow key:

    Watch

  5. Click inside the Immediate window
  6. Type timeWorked = 7.50 and press Enter
  7. Observe the update in the Watch window

    Immediate Window

  8. In the Immediate window, click the empty line, type hourlySalary = 18.24 and press Enter
  9. Check the change in the Watch window

    Immediate Window

  10. In the Immediate window, press the up arrow key to access the previously entered lines (the text lines you had typed will be displaying one after the other) until you get timeWorked
  11. Change it to timeWorked = 14 and press Enter

    Immediate Window

  12. On the Debug toolbar, click the Stop Debugging button Stop Debugging
  13. In the DOS window, press Enter to close the window and return to your programming environment
  14. Close your programming environment

Previous Copyright © 2001-2026, FunctionX Monday 02 March 2026, 13:36 Next