C# Programming: From Problem Analysis to Program Design

Arguably, the single most important tool in any development environment is the debugger. The Visual Studio debugger is very powerful and it will be well worth whatever time you put into learning how to use it well. That said, the fundamentals of debugging are very simple. The three key skills are:

  • How to set a breakpoint and how to run to that breakpoint

  • How to step into and over method calls

  • How to examine and modify the value of variables, member data, and so forth

This chapter does not reiterate the entire debugger documentation, but these skills are so fundamental that it does provide a crash (pardon the expression) course.

The debugger can accomplish the same thing in many ways, typically via menu choices, buttons, and so forth. The simplest way to set a breakpoint is to click in the lefthand margin. The IDE will mark your breakpoint with a red dot, as shown in Figure 2-5.

Figure 2-5. A breakpoint

Discussing the debugger requires code examples. The code shown here is from Chapter 5, and you are not expected to understand how it works yet (though if you program in C++ or Java, you'll probably get the gist of it).

To run the debugger, you can choose Debug->Start or just press F5. The program will compile and run to the breakpoint, at which time it will stop and a yellow arrow will indicate the next statement for execution, as in Figure 2-6.

Figure 2-6. The breakpoint hit

After you've hit your breakpoint it is easy to examine the values of various objects. For example, you can find the value of the variable i just by putting the cursor over it and waiting a moment, as shown in Figure 2-7.

Figure 2-7. Showing a value

The debugger IDE also provides a number of very useful windows, such as a Locals window that displays the values of all the local variables (see Figure 2-8).

Figure 2-8. Locals window

Intrinsic types such as integers simply show their value (see i earlier), but objects show their type and have a plus (+) sign. You can expand these objects to see their internal data, as shown in Figure 2-9. You'll learn more about objects and their internal data in upcoming chapters.

Figure 2-9. Locals window object expanded

You can step into the next method by pressing F11. Doing so steps into the DrawWindow( ) method of the Window class, as shown in Figure 2-10.

Figure 2-10. Stepping into a method

You can see that the next execution statement is now WriteLine( ) in DrawWindow( ). The autos window has updated to show the current state of the objects.

There is much more to learn about the debugger, but this brief introduction should get you started. You can answer many programming questions by writing short demonstration programs and examining them in the debugger. A good debugger is, in some ways, the single most powerful teaching tool for a programming language.

Категории