C# Basic Debugging:
Objectives
- What is Debugging in C#?
- Using breakpoints
- Inspecting variables
- Stepping through code
What is Debugging in C#?
Debugging in C# is about finding and fixing mistakes or bugs in your code to make it perform as expected.
You have to step through the code, examining variable values and find out where the problem is.
Breakpoints Usage:
These are points you set in your codes that will halt execution at those moments.
Whenever a breakpoint is hit while debugging, the debugger stops running and allows you to examine the current state of program.
To set a breakpoint:
Position your pointer on the left side of any line of code in your IDE (e.g., Visual Studio) that you want to stop executing for some time.
Or, position your pointer on the line upon which you want to pause execution and then press F9.
Inspecting Variables:
When debugging, one can check what variables contain at runtime to know what their current status is.
Whilst being halted at breakpoints; by simply hovering over them or viewing them via watch window facility provided by debugger.about
Stepping Through Code:
What is Stepping through code? are refers to the process of executing code line by line to understand its behavior.
Debugging tools provide options to step into, step over, or step out of functions during execution.
- Step Into (F11): Executes the next line of code and steps into any function calls on that line.
- Step Over (F10): Executes the next line of code but does not step into function calls; it treats them as a single step.
- Step Out (Shift + F11): Continues execution until the current function returns, then pauses again.
Example:
class Program
{
static void Main(string[] args)
{
int x = 10;
int y = 20;
int result = Add(x, y);
Console.WriteLine("Result: " + result);
}
static int Add(int a, int b)
{
int sum = a + b;
return sum;
}
}
- Set a breakpoint at the line int result = Add(x, y); in the Main method.
- Start debugging (usually by pressing F5).
- When the debugger reaches the breakpoint, you can inspect the values of x, y, and result.
- Use the debugger controls (step into, step over, step out) to navigate through the code and observe how variables change.