Practical LearningPractical Learning: Introducing Errors

  1. Start Microsoft Visual Studio
  2. Create a new Console App named ObliqueTriangles2
  3. Change the document as follows:

Stepping Into an Object

.

Practical LearningPractical Learning: Introducing Function Debugging

  1. To start debugging, on the main menu, click Debug -> Step Into.
    Move the DOS window so you can see both your code and that window

Stepping Over a Property

The Step Into feature is a good tool to monitor the behavior of variables inside a function. This also allows you to know if a function is behaving as expected. Once you have established that a function is alright, you may want to skip it. Instead of executing one line at a time, the debugger allows you to execute a whole function at a time or to execute the lines in some functions while skipping the others. To support this, you use a feature named Step Over.

To step over a function, while debugging:

As its name suggests, the Step Over feature allows you to skip a method if you know it doesn't have any problem. When debugging, you choose what methods to step into and which ones to step over.

Practical LearningPractical Learning: Stepping Over

  1. To debug, on the main menu, click Debug -> Step Into.
    Notice that the yellow button is positioned in the first line of the code
  2. To continue, on the Debug toolbar, click the Step Into button Step Into fourteen times until the type of triangle is requested in the DOS window
  3. Debugging

    F11 to continue:

    Debugging

    Notice that the debugger is positioned on the first line of the GetPrincipal() method
  4. Press F11

    Debugging

    Notice that the debugger gets in the body of the GetPrincipal() method
  5. Keep pressing F11 while inside the GetPrincipal() method, until the DOS window receives focus
  6. When asked to provide a Principal, type 21650 and press Enter:

    Debugging

  7. When focus is back to your programming environment, to end debugging, on the main menu, click Debug -> Stop Debugging
  8. To start debugging again, on the main menu, click Debug -> Step Into and notice that the yellow button is positioned in the first processed line of code
  9. To continue, on the Debug toolbar, click the Step Into button Step Into button four times:

    Debugging

  10. This time, to skip the GetPrincipal() function, on the main menu, click Debug -> Step Over
  11. Notice that, instead of the debugging moving to the function, the DOS window received focus.
    When asked to provide the principal, type 8725 and press Enter
    Notice that the focus moves back to the Code Editor at the end of the GetPrincipal() function
  12. To continue, on the Debug toolbar, click the Step Into button Step Into button three times until the line that calls the GetInterestRate() is accessed:

    Debugging

  13. To execute the function, on the Debug toolbar, click the Step Over button Step Over
  14. As the focus has moved to the DOS window, when the interest rate is requested, type 14.05 and press Enter.
    The focus moves back to the Code Editor where the GetPeriod() function is called:

    Debugging

    Notice the value of the interestRate in the Locals window
  15. To execute the GetPeriod() function, press F10 (Step Over)
  16. As the focus has moved to the DOS window, when asked to provide the number of months, type 48 and press Enter.
    The focus moves back to the Code Editor:

    Debugging

    In the Locals window, notice the period value that corresponds to 4 years
  17. To continue with Step Into, Press F11 continually. Observe the Code Editor and the DOS window:

    Debugging

    Debugging

  18. Continue stepping into code until the DOS window displays Press any key to close this window . . .
  19. To end debugging, on the Debug toolbar, click the Stop button Stop button

Debugging an Object

Introduction

Some of your applications will have objects (from a structure, a record, or a class). Here is an example:

using static System.Console;

Square sqr = new();
Rectangle rect = new(496.84, 825.97);

sqr.Side = 927.93;

WriteLine("Geometry - Square");
WriteLine("----------------------------");
WriteLine($"Side:      {sqr.Side}");
WriteLine($"Perimeter: {sqr.Perimeter}");
WriteLine($"Area:      {sqr.Area}");
WriteLine("============================");
WriteLine("Geometry - Rectangle");
WriteLine("----------------------------");
WriteLine($"Width:     {rect.Width}");
WriteLine($"Height:    {rect.Height}");
WriteLine($"Perimeter: {rect.CalculatePerimeter()}");
WriteLine($"Area:      {rect.CalculateArea()}");
WriteLine("============================");

// A Structure
internal record struct Square
{
    public double Side { get; set; }

    public double Perimeter
    {
        get
        {
            return Side * 4.00;
        }
    }

    public double Area
    {
        get
        {
            return Side * Side;
        }
    }
}

public class Rectangle
{
    public Rectangle(double width, double height)
    {
        (Width, Height) = (width, height);
    }

    public double Width  { get; init; }
    public double Height { init; get; }

    public double CalculatePerimeter()
    {
        return (Width * Height) * 2.00;
    }

    public double CalculateArea()
    {
        return Width * Width;
    }
}

When debugging involves an object, the Locals window includes a record for an object. Such a record displays a right-pointing button on the left of the name of the object. Here is an example:

Debugging

Debugging

Debugging

In this case, to show the variables, you can expand the node. To do this, you can click the arrow icon. This would show the fields under the variable name and the name of the class between curly brackets under the Value column:

The Locals Window - The Name Column

The Type of a Variable

The Type column shows the data type of the variable. If the variable is an object (from a class, a record, a structure, or an interface), the name of the type shows in the Type column.

Debugging Fundamentals

Practical LearningPractical Learning: Examining Local Variables

  1. While the Code Editor is displaying the code you typed, on the main menu, click Debug -> Step Into.
    If the Locals window is not displaying, on the main menu, click Debug -> Window -> Locals
  2. To perform the instructions in this section, move the windows to make sure you can see the Code Editor, the Locals window, and the DOS window. Here is an example:

    Debugging

  3. Notice the yellow arrow button on the left of the declaration of the principal variable.
    Notice that the Locals window displays one entry: the principal variable.
    Notice that the DOS window shows a blinking caret.
    To end debugging, on the main menu, click Debug -> Stop Debugging
  4. To continue debugging, on the Standard toolbar, click the Step Into button Step Into
  5. To continue debugging, Press F11.
    At some point, text will display in the DOS window
  6. Keep pressing F11 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

    Debugging

  7. When asked to enter a value for the principal, type 6500 and press Enter
  8. 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
  9. Press F11 again
  10. When the caret sttars blinking in the DOS window as you are asked to provide the interest rate, type 12.65 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

  11. Press F11
  12. Press F11 again
  13. The focus moves to the DOS window. When the number of months is requested, type 36 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

  14. Press F11

    Debugging

  15. Press F11

    Debugging

  16. Press F11

    Debugging

  17. Continue pressing F11 until the DOS window displays a summary of the calculations:
    ============================
    Loan Summary
    =--------------------------=
    Principal:       6500.00
    Interest Rate:   12.65 %
    Period For:      36 months
    Interest Amount: 2466.75
    Future Value:    8966.75
    ============================
  18. Press Enter to get back to your programming environment
  19. Press F11 to end

Running to a Point

When executing a program, you can specify a section or line where you want the execution to pause, for any reason you judge necessary. This approach is useful if you have checked code up to a certain point and it looked alright. If you are not sure about code starting at a certain point, this can be your starting point.

To execute code up to a certain point

Practical LearningPractical Learning: Running to a Point

  1. In the code, right-click the futureValue = principal + interestAmount; line and click Run To Cursor.
    Make sure you can see the Code Editor, the Locals window, and the DOS window:

    Debugging - Run to Cursor

  2. When requested, enter the following values and press Enter after entering each:
    Principal: 21466.85
    Interest Rate: 12.25
    Number of Months: 60

    Debugging - Run to Cursor

    The focus moves to Microsoft Visual Studio and the Locals window:

    Debugging - Run to Cursor

  3. Press F5 to continue
    ============================
    Loan Summary
    =--------------------------=
    Principal:       21466.85
    Interest Rate:   12.25%
    Period For:      60 months
    Interest Amount: 13148.45
    Future Value:    34615.30
    ============================
    
    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 . . .
  4. To close the DOS window, press any key, such as Q
  5. Close your programming environment
====================================================================================

Using Separate Files

Instead of just one class or one file, we have learned, and will continue learning, that, to organize your project, you can create the classes of your project in different files. When you debug a project that uses different classes or files that contain classes, the debugger is aware of the objects and where they are created. As we will learn later, there are various windows that assist you with identifying the objects of your project. As a result, the tools such as the Locals window display their contents accordingly.

As you know already, the starting point of a C# application is the primary document that displays when you have created a Console App project (in previous C# console applications, that would be a class that contains a method named Main). If you start debugging an application that uses many code files (files that contain classes), the debugger must first identify the primary document of the project (if you are debugging a normal console application but the debugger cannot find a file that contains the Main() function, you would receive an error, indicating that your project does not contain an entry point).

Practical LearningPractical Learning: Debugging Classes

  1. Change the LoanEvaluation.cs document as follows:
    using WattsALoan02.Models;
    using static System.Console;
    
    LoanEvaluation evaluation = new LoanEvaluation();
    
    Title = "Watts A Loan?";
    
    WriteLine("This application allows you to evaluate a loan");
    evaluation.IdentifyEmployee();
    evaluation.IdentifyCustomer();
    
    Clear();
    
    evaluation.GetLoanValues();
    
    Clear();
    
    evaluation.Show();
    
    public class LoanEvaluation
    {
        private Employee        clerk;
        private Customer        client;
        private LoanInformation loan;
    
        public LoanEvaluation()
        {
            clerk  = new Employee();
            client = new Customer();
            loan   = new LoanInformation();
        }
    
        public void IdentifyEmployee()
        {
            WriteLine("Enter the following pieces of information " +
                              "about the employee who prepared this loan.");
            Write("Employee #: ");
            clerk.employeeNumber = long.Parse(ReadLine()!);
            Write("First Name: ");
            clerk.firstName      = ReadLine()!;
            Write("Last Name:  ");
            clerk.lastName       = ReadLine()!;
            Write("Title:      ");
            clerk.title          = ReadLine()!;
        }
    
        public void IdentifyCustomer()
        {
            WriteLine("Enter the following pieces of information " +
                      "about the customer for whom this loan was prepared.");
            Write("Customer Name: ");
            client.fullName    = ReadLine()!;
            Write("Phone Number:  ");
            client.phoneNumber = ReadLine()!;
        }
    
        public void GetLoanValues()
        {
            WriteLine("Enter the following pieces of information " +
                      "about the values used for the loan.");
    
            Write("Enter the principal: ");
            loan.Principal    = double.Parse(ReadLine()!);
      
            Write("Enter the interest rate: ");
            loan.InterestRate = double.Parse(ReadLine()!) / 100;
    
            Write("Enter the number of months: ");
            loan.Period       = double.Parse(ReadLine()!) / 12;
        }
    
        public void Show()
        {
            loan.InterestAmount = loan.Principal * loan.InterestRate * loan.Period;
            loan.FutureValue    = loan.Principal + loan.InterestAmount;
    
            WriteLine("======================================");
            WriteLine("Loan Summary");
            WriteLine("=------------------------------------=");
            WriteLine("Prepared by:  {0} - {1}\n              {2}",
                              clerk.employeeNumber,
                              clerk.GetEmployeeName(), clerk.title);
            WriteLine("=------------------------------------=");
            WriteLine("Prepared for: {0}\n              {1}",
                              client.fullName, client.phoneNumber);
            WriteLine("=------------------------------------=");
            WriteLine("Principal:       {0:F}", loan.Principal);
            WriteLine("Interest Rate:   {0:P}", loan.InterestRate);
            WriteLine("Period For:      {0} months", loan.Period * 12);
            WriteLine("Interest Amount: {0:F}", loan.InterestAmount);
            WriteLine("Future Value:    {0:F}", loan.FutureValue);
            WriteLine("======================================");
        }
    }
  2. To start debugging, on the main menu, click Debug and click Step Into.
    If you don't see the Locals window, to display it, on the main menu, click Debug -> Window -> Locals
  3. Move the windows to make sure you can see the Code Editor, the Locals window, and the DOS window
  4. Notice that the debugging yellow arrow indicator is positioned on the left of the first variable declaration.
    Notice that at this time, the Locals window contains only the evaluation variable whose value is null:

    The Locals Window

    At this time, the DOS window shows a blinking caret
  5. To continue debugging, on the main menu, click Debug -> Step Into
  6. Again, on the main menu, click Debug -> Step Into.
    Notice that the debugger is in the LoanEvaluation.cs file and on the opening curly bracket of its constructor
  7. In the Locals window, click the button of the this node to expand it. Notice that it shows the global variables of the class:

    The Locals Window

  8. To continue debugging, on the Standard toolbar, click the Step Into button Step Into three times.
    Notice that the execution switches to the constructor of the Employee class in the Employee.cs file
  9. In the Locals window, click the button of the this node to expand it:

    The Locals Window

  10. To continue debugging, press F11 seven times.
    The debugging returns to the LoanEvaluation.cs file and focuses on the clerk variable that is of type Employee
  11. On the Standard toolbar, click the Step Into button Step Into twice.
    The debugging moves to the constructor of the Customer class in the Customer.cs file
  12. Press F11 five times.
    The debugging returns to the client variable in the LoanEvaluation.cs file
  13. Press F11 three times.
    The debugging remains in the primary document but the focus moves back to the first variable
  14. Notice the string in the title bar of the DOS window.
    Press F11 twice.
    Notice that the title bar of the DOS window has changed
  15. In the Locals window, click all the buttons to show the current values of the variables for the Employee, the Customer, and the LoanInformation variables::

    The Locals Window

  16. Pressing F11 a few times (probably 6 times) until the title bar of the DOS window indicates that it has focus and you are asked to enter an employee number (you should see the caret blinking on Employee #:)
  17. When asked for an employee number, type 20584 and press Enter
  18. The focus moves back to the Code Editor.
    Notice that the value of the employee number has changed in the Locals window.
    Press F11 twice.
    The focus moves back to the DOS window
  19. For the First Name, type Ahmed and press Enter
  20. The focus moves back to the Code Editor.
    Press F11 twice.
    The focus moves back to the DOS window
  21. For the Last Name, type Mahmouda and press Enter
  22. The focus moves back to the Code Editor.
    Press F11 twice.
    The focus moves back to the DOS window
  23. For the Title, type Account Representative and press Enter
  24. The focus moves back to the Code Editor.
    Press F11 seven times.
    The focus moves back to the DOS window
  25. When asked to provide a customer name, type Lauren Sachs and press Enter
  26. The focus moves back to the Code Editor.
    press F11 twice.
    The focus moves back to the DOS window
  27. For the Phone Number, type (103) 438-6243 and press Enter
  28. The focus moves back to the Code Editor.
    Press F11 a few times (probably 8 times) until the DOS window receives focus
  29. When prompted for the value of the principal, type 24750 and press Enter
  30. The focus moves to the Code Editor.
    Notice that the value of the principal has changed in the Locals grid.
    Press F11 twice
  31. When the focus moves to the DOS window, when you are asked to provide the interest rate, type 11.35 and press Enter
  32. Press F11 twice
  33. The focus moves to the DOS window.
    For the number of months, type 60 and press Enter
  34. Expand all nodes in the Locals window
  35. Press F11.
    Observe the values in the Locals window and see the new lines in the DOS window
  36. Press F11 continuously and observe the changes in the DOS window
  37. Keep pressing F11 until the caret is blinking on the "Press any key to close this window . . ." line in the DOS window. When that happens, close the DOS window

Practical LearningPractical Learning: Using the Immediate Window

  1. To start a new project, on the main menu, click File -> New -> Project
  2. In the middle list, click Empty Project
  3. Change the Name to PayrollEvaluation1
  4. Click OK
  5. To create a file, in the Solution Explorer, right-click PayrollEvaluation1 -> Add -> New Item...
  6. In the middle list, click Code File
  7. Change the Name to Evaluation and click Add
  8. In the empty document, type the following:
    double grossPay = 0D;
    double timeWorked = 0D;
    double hourlySalary = 0.00D;
    // double federalIncomeTax = 0.00D;
    // const double FICATaxRate = 0.0765; // 7.65%
    // double FICATaxAmount = 0.00D;
    double totalDeductions = 0.0D;
    double netPay = 0.00D;
    
    Title = "Payroll Evaluation";
    /*      
    	WriteLine("To test a payroll, enter the following pieces of information");
            Write("Time Wored:    ");
            timeWorked = double.Parse(ReadLine());
            Write("Hourly Salary: ");
            hourlySalary = double.Parse(ReadLine());
            Write("Enter the amount of the deductions: ");
            totalDeductions = double.Parse(ReadLine());
            */
            
    grossPay = hourlySalary * timeWorked;
    netPay = grossPay - totalDeductions;
    Clear();
    
    WriteLine("=======================");
    WriteLine("Payroll Evaluation");
    WriteLine("-----------------------");
    WriteLine("Time Worked:   {0, 7}", timeWorked.ToString("F"));
    WriteLine("Hourly Salary: {0, 7}", hourlySalary.ToString("F"));
    WriteLine("Gross Pay:     {0, 7}", grossPay.ToString("F"));
    WriteLine("Deductions:    {0, 7}", totalDeductions.ToString("F"));
    WriteLine("Net Pay:       {0, 7}", netPay.ToString("F"));
    WriteLine("=======================\n");
  9. To execute the application, on the main menu, click Debug -> Start Debugging.
    Notice that all values are 0:

    Payroll Evaluation

  10. Press Enter to close the DOS window and return to your programming environment
  11. To step into code, on the main menu, click Debug -> Step Into
  12. If the Imediate window is not displaying, on the main menu, click Debug -> Windows -> Immediate.
    Just in case, right-click inside the Immediate window and click Clear All.
    Press F11 to step into code
  13. Continue pressing the key (3 times) to step into code until you get to the line double netPay = 0.00D;
  14. Click inside the Immediate window
  15. Type timeWorked = 42.50 and press Enter
  16. Type hourlySalary = 24.65 and press Enter
  17. Type totalDeductions = 286.50 and press Enter

    Immediate Window

  18. Press F11 three or four times to step into code until you get to the line that has Clear();

    Debugging

  19. Click the next empty line in the Immediate window
  20. Type ?grossPay and press Enter
  21. Type ?netPay and press Enter

    Immediate Window

  22. Press the F11 key to step into code a few times until the DOS window gets focus

    Immediate Window

  23. Press Enter to return to Microsoft Visual C#
  24. Press F11 continuously until you get to the end of code and the DOS window closes

Previous Copyright © 2010-2026, FunctionX Wednesday 15 October 2025, 22:32 Next