Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Debugging


Share

Debugging

In the previous chapter, you learned about the three kinds of errors. Debugging means to find and fix the errors (bugs) in a program.

Compile errors are often easy to fix, because C# tells you the line. Runtime errors and logic errors are harder: you have to find out where the program goes wrong.

This chapter shows four simple ways to do that:

  • Print values with Console.WriteLine()
  • Check one step at a time
  • Read the error message
  • Use a breakpoint in Visual Studio

Print Values

The easiest way to debug is to print the values of your variables. Then you can see what the program really does, not what you think it does.

This code should add up three prices. The total should be 60, but the program prints 50:

Example

int[] prices = {10, 20, 30};
int total = 0;
for (int i = 1; i < prices.Length; i++)
{
  total = total + prices[i];
}
Console.WriteLine(total);  // 50

Try it Yourself »

To find the bug, add a Console.WriteLine() inside the loop. It prints the index and the price each time the loop runs:

Example

int[] prices = {10, 20, 30};
int total = 0;
for (int i = 1; i < prices.Length; i++)
{
  Console.WriteLine("i is " + i + ", price is " + prices[i]);
  total = total + prices[i];
}
Console.WriteLine(total);

Try it Yourself »

The output shows i is 1 and i is 2, but never i is 0. So the loop never adds the first price, 10.

The first index in an array is 0, so the loop must start at int i = 0. Fix the loop, and remove the debug line when you are done:

Example

int[] prices = {10, 20, 30};
int total = 0;
for (int i = 0; i < prices.Length; i++)
{
  total = total + prices[i];
}
Console.WriteLine(total);  // 60

Try it Yourself »



Check One Step at a Time

When a program stops with an error, you need to find the line that causes it. Print a short message between the steps of your program. The last message you see tells you how far the program got.

This code shares 100 points between the players:

Example

int points = 100;
int players = 0;
Console.WriteLine("Step 1");
int pointsEach = points / players;
Console.WriteLine("Step 2");
Console.WriteLine(pointsEach);

The output looks like this:

Step 1
System.DivideByZeroException: Attempted to divide by zero.

"Step 1" is printed, but "Step 2" is not. So the problem is in the line between them: players is 0, and you cannot divide by zero.


Read the Error Message

When you get an error message, read it carefully. It tells you what went wrong, and often where. The Errors chapter shows how to read the line number and the error code.

This table shows some common error messages, and what to check:

Error messageWhat to check
; expectedA semicolon is missing. Look at the end of the line in the message, and the line before it.
The name ... does not exist in the current contextIs the variable created before you use it? Is the name spelled the same way?
Cannot implicitly convert typeThe value does not match the type of the variable.
DivideByZeroExceptionA division where the number you divide by is 0.
IndexOutOfRangeExceptionAn array index that does not exist. The last index is Length - 1.

Use a Breakpoint

Visual Studio (the program from the Get Started chapter) has a built-in debugger. A debugger lets you pause the program and look at the values of your variables, line by line.

A breakpoint is a line where the program pauses. This is how you use one:

  1. Click in the gray area to the left of a line number. A red dot appears. This is the breakpoint.
  2. Press F5 to start the program with the debugger.
  3. The program stops at the line with the red dot, before that line runs. The line turns yellow.
  4. Move the mouse over a variable to see its value. The Locals window at the bottom also shows the values of all variables.
  5. Press F10 to run the next line. Watch how the values change.

Press F5 again to let the program run to the end. To remove the breakpoint, click the red dot.

In the next chapter, Exceptions, you will learn how to handle runtime errors, so the program does not stop.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.