Share via


Tutorial: Learn to debug C# code using Visual Studio

This article introduces the features of the Visual Studio debugger in a step-by-step walkthrough. If you want a higher-level view of the debugger features, see First look at the debugger. When you debug your app, it usually means that you're running your application with the debugger attached. When you do this task, the debugger provides many ways to see what your code is doing while it runs. You can step through your code and look at the values stored in variables, you can set watches on variables to see when values change, you can examine the execution path of your code, see whether a branch of code is running, and so on. If this exercise is the first time that you've tried to debug code, you might want to read Debugging for absolute beginners before going through this article.

Although the demo app is C#, most of the features are applicable to C++, Visual Basic, F#, Python, JavaScript, and other languages supported by Visual Studio (F# doesn't support Edit-and-continue. F# and JavaScript don't support the Autos window). The screenshots are in C#.

In this tutorial, you will:

  • Start the debugger and hit breakpoints.
  • Learn commands to step through code in the debugger
  • Inspect variables in data tips and debugger windows
  • Examine the call stack

Prerequisites

If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Create a project

First, you create a .NET Core console application project. The project type comes with all the template files you need, before you've even added anything!

  1. Open Visual Studio. If the start window isn't open, select File > Start Window.

  2. On the start window, select Create a new project.

Visual Studio opens your new project.

Create the application

In Program.cs, replace all of the default code with the following code:

using System;

class ArrayExample
{
   static void Main()
   {
      char[] letters = { 'f', 'r', 'e', 'd', ' ', 's', 'm', 'i', 't', 'h'};
      string name = "";
      int[] a = new int[10];
      for (int i = 0; i < letters.Length; i++)
      {
         name += letters[i];
         a[i] = i + 1;
         SendMessage(name, a[i]);
      }
      Console.ReadKey();
   }

   static void SendMessage(string name, int msg)
   {
      Console.WriteLine("Hello, " + name + "! Count to " + msg);
   }
}

Start the debugger!

Set a breakpoint and start the debugger

Restart your app quickly

Inspect variables with the Autos and Locals windows

Set a watch

Examine the call stack

Next steps

In this tutorial, you've learned how to start the debugger, step through code, and inspect variables. You might want to get a high-level look at debugger features along with links to more information.