Create Windows Forms With C#
Create Windows Forms With C#
C# Tutorials
Overview
About Visual Studio
About the code editor
About projects and solutions
More Visual Studio features
Create an app
Create your first C# app
Part 1: Create a C# console app
Part 2: Extend your C# console app
Create a web app
Create a UWP app
Create a WPF application
Create a Windows Forms app
Video Tutorial - Create an ASP.NET Core Web App
1 - Install Visual Studio
2 - Create your first ASP.NET Core web app
3 - Work with data
4 - Expose a web API
5 - Deploy your ASP.NET Core app to Azure
Learn Visual Studio
Run a program
Open a project from a repo
Write and edit code
Compile and build
Debug your code
Unit testing
Deploy your project
Access data
Welcome to the Visual Studio IDE | C#
10/22/2020 • 14 minutes to read • Edit Online
The Visual Studio integrated development environment is a creative launching pad that you can use to edit, debug,
and build code, and then publish an app. An integrated development environment (IDE) is a feature-rich program
that can be used for many aspects of software development. Over and above the standard editor and debugger
that most IDEs provide, Visual Studio includes compilers, code completion tools, graphical designers, and many
more features to ease the software development process.
This image shows Visual Studio with an open project and several key tool windows you'll likely use:
Solution Explorer (top right) lets you view, navigate, and manage your code files. Solution Explorer can
help organize your code by grouping the files into solutions and projects.
The editor window (center), where you'll likely spend a majority of your time, displays file contents. This is
where you can edit code or design a user interface such as a window with buttons and text boxes.
The Output window (bottom center) is where Visual Studio sends notifications such as debugging and error
messages, compiler warnings, publishing status messages, and more. Each message source has its own tab.
Team Explorer (bottom right) lets you track work items and share code with others using version control
technologies such as Git and Team Foundation Version Control (TFVC).
Editions
Visual Studio is available for Windows and Mac. Visual Studio for Mac has many of the same features as Visual
Studio 2017, and is optimized for developing cross-platform and mobile apps. This article focuses on the Windows
version of Visual Studio 2017.
There are three editions of Visual Studio: Community, Professional, and Enterprise. See Compare Visual Studio
editions to learn about which features are supported in each edition.
Visual Studio is available for Windows and Mac. Visual Studio for Mac has many of the same features as Visual
Studio 2019, and is optimized for developing cross-platform and mobile apps. This article focuses on the Windows
version of Visual Studio 2019.
There are three editions of Visual Studio 2019: Community, Professional, and Enterprise. See Compare Visual
Studio editions to learn about which features are supported in each edition.
Code Cleanup
With the click of a button, format your code and apply any code fixes suggested by your code style settings,
.editorconfig conventions, and Roslyn analyzers. Code Cleanup helps you resolve issues in your code
before it goes to code review. (Currently available for C# code only.)
Refactoring
Refactoring includes operations such as intelligent renaming of variables, extracting one or more lines of
code into a new method, changing the order of method parameters, and more.
IntelliSense
IntelliSense is a term for a set of features that displays information about your code directly in the editor
and, in some cases, write small bits of code for you. It's like having basic documentation inline in the editor,
which saves you from having to look up type information elsewhere. IntelliSense features vary by language.
For more information, see C# IntelliSense, Visual C++ IntelliSense, JavaScript IntelliSense, and Visual Basic
IntelliSense. The following illustration shows how IntelliSense displays a member list for a type:
For information and productivity tips, see How to use Visual Studio search.
Live Share
Collaboratively edit and debug with others in real time, regardless of what your app type or programming
language. You can instantly and securely share your project and, as needed, debugging sessions, terminal
instances, localhost web apps, voice calls, and more.
Call Hierarchy
The Call Hierarchy window shows the methods that call a selected method. This can be useful information
when you're thinking about changing or removing the method, or when you're trying to track down a bug.
CodeLens
CodeLens helps you find references to your code, changes to your code, linked bugs, work items, code
reviews, and unit tests, all without leaving the editor.
Go To Definition
The Go To Definition feature takes you directly to the location where a function or type is defined.
Peek Definition
The Peek Definition window shows the definition of a method or type without actually opening a separate
file.
Create a program
Let's dive in and create a simple program.
1. Open Visual Studio.
2. On the menu bar, choose File > New > Project .
The New Project dialog box shows several project templates. A template contains the basic files and
settings needed for a given project type.
3. Choose the .NET Core template category under Visual C# , and then choose the Console App (.NET
Core) template. In the Name text box, type HelloWorld , and then select the OK button.
NOTE
If you don't see the .NET Core category, you need to install the .NET Core cross-platform development
workload. To do this, choose the Open Visual Studio Installer link on the bottom left of the New Project dialog.
After Visual Studio Installer opens, scroll down and select the .NET Core cross-platform development workload,
and then select Modify .
Visual Studio creates the project. It's a simple "Hello World" application that calls the Console.WriteLine()
method to display the literal string "Hello World!" in the console (program output) window.
Shortly, you should see something like the following:
The C# code for your application shows in the editor window, which takes up most of the space. Notice that
the text is automatically colorized to indicate different parts of the code, such as keywords and types. In
addition, small, vertical dashed lines in the code indicate which braces match one another, and line numbers
help you locate code later. You can choose the small, boxed minus signs to collapse or expand blocks of code.
This code outlining feature lets you hide code you don't need, helping to minimize onscreen clutter. The
project files are listed on the right side in a window called Solution Explorer .
There are other menus and tool windows available, but let's move on for now.
4. Now, start the app. You can do this by choosing Star t Without Debugging from the Debug menu on the
menu bar. You can also press Ctrl +F5 .
Visual Studio builds the app, and a console window opens with the message Hello World! . You now have a
running app!
5. To close the console window, press any key on your keyboard.
6. Let's add some additional code to the app. Add the following C# code before the line that says
Console.WriteLine("Hello World!"); :
This code displays What is your name? in the console window, and then waits until the user enters some
text followed by the Enter key.
7. Change the line that says Console.WriteLine("Hello World!"); to the following code:
Console.WriteLine($"\nHello {name}!");
8. Run the app again by selecting Debug > Star t Without Debugging or by pressing Ctrl +F5 .
Visual Studio rebuilds the app, and a console window opens and prompts you for your name.
9. Enter your name in the console window and press Enter .
10. Press any key to close the console window and stop the running program.
1. Open Visual Studio.
The start window appears with various options for cloning a repo, opening a recent project, or creating a
brand new project.
2. Choose Create a new project .
The Create a new project window opens and shows several project templates. A template contains the
basic files and settings needed for a given project type.
3. To find the template we want, type or enter .net core console in the search box. The list of available
templates is automatically filtered based on the keywords you entered. You can further filter the template
results by choosing C# from the Language drop-down list. Select the Console App (.NET Core) template,
and then choose Next .
4. In the Configure your new project window, enter HelloWorld in the Project name box, optionally
change the directory location for your project files, and then choose Create .
Visual Studio creates the project. It's a simple "Hello World" application that calls the Console.WriteLine()
method to display the literal string "Hello World!" in the console (program output) window.
Shortly, you should see something like the following:
The C# code for your application shows in the editor window, which takes up most of the space. Notice that
the text is automatically colorized to indicate different parts of the code, such as keywords and types. In
addition, small, vertical dashed lines in the code indicate which braces match one another, and line numbers
help you locate code later. You can choose the small, boxed minus signs to collapse or expand blocks of code.
This code outlining feature lets you hide code you don't need, helping to minimize onscreen clutter. The
project files are listed on the right side in a window called Solution Explorer .
There are other menus and tool windows available, but let's move on for now.
5. Now, start the app. You can do this by choosing Star t Without Debugging from the Debug menu on the
menu bar. You can also press Ctrl +F5 .
Visual Studio builds the app, and a console window opens with the message Hello World! . You now have a
running app!
6. To close the console window, press any key on your keyboard.
7. Let's add some additional code to the app. Add the following C# code before the line that says
Console.WriteLine("Hello World!"); :
This code displays What is your name? in the console window, and then waits until the user enters some
text followed by the Enter key.
8. Change the line that says Console.WriteLine("Hello World!"); to the following code:
Console.WriteLine($"\nHello {name}!");
9. Run the app again by selecting Debug > Star t Without Debugging or by pressing Ctrl +F5 .
Visual Studio rebuilds the app, and a console window opens and prompts you for your name.
10. Enter your name in the console window and press Enter .
11. Press any key to close the console window and stop the running program.
3. Select the light bulb icon to show the available Quick Actions. Select Rename 'name' to 'username' .
The variable is renamed across the project, which in our case is only two places.
4. Now let's take a look at IntelliSense. Below the line that says Console.WriteLine($"\nHello {username}!"); ,
type DateTime now = DateTime. .
A box displays the members of the DateTime class. In addition, the description of the currently selected
member displays in a separate box.
5. Select the member named Now , which is a property of the class, by double-clicking on it or pressing Tab .
Complete the line of code by adding a semi-colon to the end.
6. Below that, type in or paste the following lines of code:
7. Next, we'll use refactoring again to make the code a little more concise. Click on the variable now in the line
DateTime now = DateTime.Now; .
Notice that a little screwdriver icon appears in the margin on that line.
8. Click the screwdriver icon to see what suggestions Visual Studio has available. In this case, it's showing the
Inline temporary variable refactoring to remove a line of code without changing the overall behavior of the
code:
10. Run the program again by pressing Ctrl +F5 . The output looks something like this:
Debug code
When you write code, you need to run it and test it for bugs. Visual Studio's debugging system lets you step
through code one statement at a time and inspect variables as you go. You can set breakpoints that stop execution
of the code at a particular line. You can observe how the value of a variable changes as the code runs, and more.
Let's set a breakpoint to see the value of the username variable while the program is "in flight".
1. Find the line of code that says Console.WriteLine($"\nHello {username}!"); . To set a breakpoint on this line
of code, that is, to make the program pause execution at this line, click in the far left margin of the editor. You
can also click anywhere on the line of code and then press F9 .
A red circle appears in the far left margin, and the code is highlighted in red.
2. On the Environment > General options page, change the Color theme selection to Dark , and then
choose OK .
The color theme for the entire IDE changes to Dark .
To learn about other ways you can personalize the IDE, see Personalize Visual Studio.
Next steps
Explore Visual Studio further by following along with one of these introductory articles:
Learn to use the code editor
Learn about projects and solutions
See also
Discover more Visual Studio features
Visit visualstudio.microsoft.com
Read The Visual Studio blog
Learn to use the code editor with C#
10/22/2020 • 6 minutes to read • Edit Online
In this 10-minute introduction to the code editor in Visual Studio, we'll add code to a file to look at some of the ways
that Visual Studio makes writing, navigating, and understanding C# code easier.
TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
This article assumes you're already familiar with C#. If you aren't, we suggest you look at a tutorial such as Get
started with C# and ASP.NET Core in Visual Studio first.
TIP
To follow along with this article, make sure you have the C# settings selected for Visual Studio. For information about
selecting settings for the integrated development environment (IDE), see Select environment settings.
The list includes snippets for creating a class, a constructor, a for loop, an if or switch statement, and more.
Comment out code
The toolbar, which is the row of buttons under the menu bar in Visual Studio, can help make you more productive
as you code. For example, you can toggle IntelliSense completion mode (IntelliSense is a coding aid that displays a
list of matching methods, amongst other things), increase or decrease a line indent, or comment out code that you
don't want to compile. In this section, we'll comment out some code.
string[] morewords = {
"over",
"the",
"lazy",
"dog"
};
2. We're not using the morewords variable, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing semi-colon,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .
The C# comment characters // are added to the beginning of each selected line to comment out the code.
The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again, click the
same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called Outlining and is
especially useful when you're collapsing long methods or entire classes.
View symbol definitions
The Visual Studio editor makes it easy to inspect the definition of a type, method, etc. One way is to navigate to the
file that contains the definition, for example by choosing Go to Definition or pressing F12 anywhere the symbol
is referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use Peek
Definition. Let's peek at the definition of the string type.
1. Right-click on any occurrence of string and choose Peek Definition from the content menu. Or, press
Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up window,
or even peek at the definition of another type from the peeked code.
2. Close the peeked definition window by choosing the small box with an "x" at the top right of the pop-up
window.
You see IntelliSense show you Quick Info about the query symbol.
2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code. You can even practice using code snippets again by
entering cw and then pressing Tab twice to generate the Console.WriteLine code.
3. Press Enter .
Both occurrences of words have been renamed, as well as the reference to words in the code comment.
Next steps
Learn about projects and solutions
See also
Code snippets
Navigate code
Outlining
Go To Definition and Peek Definition
Refactoring
Use IntelliSense
Learn about projects and solutions
2/25/2020 • 8 minutes to read • Edit Online
In this introductory article, we'll explore what it means to create a solution and a project in Visual Studio. A
solution is a container that's used to organize one or more related code projects, for example a class library project
and a corresponding test project. We'll look at the properties of a project and some of the files it can contain. We'll
also create a reference from one project to another.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
We'll construct a solution and project from scratch as an educational exercise to understand the concept of a
project. In your general use of Visual Studio, you'll likely use some of the various project templates that Visual
Studio offers when you create a new project.
NOTE
Solutions and projects aren't required to develop apps in Visual Studio. You can also just open a folder that contains code
and start coding, building, and debugging. For example, if you clone a GitHub repo, it might not contain Visual Studio
projects and solutions. For more information, see Develop code in Visual Studio without projects or solutions.
NOTE
If you don't see Visual C# in the left pane of the dialog box, you must install the .NET desktop development
Visual Studio workload. Visual Studio uses workload-based installation to install only the components you need for
the type of development you do. An easy way to install a new workload is to choose the Open Visual Studio
Installer link in the bottom left corner of the Add New Project dialog box. After Visual Studio Installer launches,
choose the .NET desktop development workload and then the Modify button.
1. From the right-click or context menu of Solution 'QuickSolution' in Solution Explorer , choose Add >
New Project .
A dialog box opens that says Add a new project .
2. Enter the text empty into the search box at the top, and then select C# under Language .
3. Select the Empty Project (.NET Framework) template, and then choose Next .
4. Name the project QuickDate , then choose Create .
A project named QuickDate appears beneath the solution in Solution Explorer . Currently it contains a
single file called App.config.
NOTE
If you don't see the Empty Project (.NET Framework) template, you must install the .NET desktop
development Visual Studio workload. Visual Studio uses workload-based installation to install only the components
you need for the type of development you do. An easy way to install a new workload when you're creating a new
project is to choose the Install more tools and features link under the text that says Not finding what you're
looking for? . After Visual Studio Installer launches, choose the .NET desktop development workload and then
the Modify button.
namespace QuickDate
{
internal class Calendar
{
static void Main(string[] args)
{
DateTime now = GetCurrentDate();
Console.WriteLine($"Today's date is {now}");
Console.ReadLine();
}
You don't need to understand what the code does, but if you want, you can run the program by pressing
Ctrl +F5 and see that it prints today's date to the console (or standard output) window.
2. In the Add a new project dialog box, enter the text unit test into the search box at the top, and then select
C# under Language .
3. Choose the MSTest Test Project (.NET Core) project template, and then choose Next .
4. Name the project QuickTest , and then choose Create .
A second project is added to Solution Explorer , and a file named UnitTest1.cs opens in the editor.
namespace QuickTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestGetCurrentDate()
{
Assert.AreEqual(DateTime.Now.Date, QuickDate.Calendar.GetCurrentDate());
}
}
}
You'll see a red squiggle under some of the code. We'll fix this error by making the test project a friend
assembly to the QuickDate project.
2. Back in the QuickDate project, open the Calendar.cs file if it's not already open. Add the following using
statement and InternalsVisibleToAttribute attribute to the top of the file to resolve the error in the test
project.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("QuickTest")]
Project properties
The line in the Calendar.cs file that contains the InternalsVisibleToAttribute attribute references the assembly name
(file name) of the QuickTest project. The assembly name might not always be the same as the project name. To
find the assembly name of a project, open the project properties.
1. In Solution Explorer , select the QuickTest project. From the right-click or context menu, select
Proper ties , or just press Alt +Enter .
The property pages for the project open on the Application tab. The property pages contain various
settings for the project. Notice that the assembly name of the QuickTest project is indeed "QuickTest". If
you wanted to change it, this is where you'd do that. Then, when you build the test project, the name of the
resulting binary file would change from QuickTest.dll to whatever you chose.
2. Explore some of the other tabs of the project's property pages, such as Build and Debug . These tabs are
different for different types of projects.
Next steps
If you want to check that your unit test is working, choose Test > Run > All Tests from the menu bar. A window
called Test Explorer opens, and you should see that the TestGetCurrentDate test passes.
TIP
If Test Explorer doesn't open automatically, open it by choosing Test > Windows > Test Explorer from the menu bar.
TIP
If Test Explorer doesn't open automatically, open it by choosing Test > Test Explorer from the menu bar.
See also
Create projects and solutions
Manage project and solution properties
Manage references in a project
Develop code in Visual Studio without projects or solutions
Visual Studio IDE overview
Features of Visual Studio
10/22/2020 • 7 minutes to read • Edit Online
The Visual Studio IDE overview article gives a basic introduction to Visual Studio. This article describes features that
might be more appropriate for experienced developers, or those developers who are already familiar with Visual
Studio.
Modular installation
Visual Studio's modular installer enables you to choose and install workloads. Workloads are groups of features
needed for the programming language or platform you prefer. This strategy helps to keep the footprint of the
Visual Studio installation smaller, which means it installs and updates faster too.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
To learn more about setting up Visual Studio on your system, see Install Visual Studio.
After you install the Azure development workload, the following Cloud templates for C# are available in the
New Project dialog:
Visual Studio's Cloud Explorer lets you view and manage your Azure-based cloud resources within Visual Studio.
These resources may include virtual machines, tables, SQL databases, and more. Cloud Explorer shows the Azure
resources in all the accounts managed under the Azure subscription you're logged into. And if a particular
operation requires the Azure portal, Cloud Explorer provides links that take you to the place in the portal where
you need to go.
You can leverage Azure services for your apps using Connected Ser vices such as:
Active Directory connected service so users can use their accounts from Azure Active Directory to connect to
web apps
Azure Storage connected service for blob storage, queues, and tables
Key Vault connected service to manage secrets for web apps
The available Connected Ser vices depend on your project type. Add a service by right-clicking on the project in
Solution Explorer and choosing Add > Connected Ser vice .
For more information, see Move to the cloud With Visual Studio and Azure.
You can also automate your build process to build the code that the devs on your team have checked into version
control. For example, you can build one or more projects nightly or every time that code is checked in. For more
information, see Azure Pipelines.
See also
Visual Studio IDE overview
What's new in Visual Studio 2017
What's new in Visual Studio 2019
Tutorial: Create a simple C# console app in Visual
Studio
10/22/2020 • 12 minutes to read • Edit Online
In this tutorial for C#, you'll use Visual Studio to create and run a console app and explore some features of the
Visual Studio integrated development environment (IDE) while you do so.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
Create a project
To start, we'll create a C# application project. The project type comes with all the template files you'll need, before
you've even added anything!
1. Open Visual Studio 2017.
2. From the top menu bar, choose File > New > Project . (Alternatively, press Ctrl +Shift +N ).
3. In the left pane of the New Project dialog box, expand C# , and then choose .NET Core . In the middle pane,
choose Console App (.NET Core) . Then name the file Calculator .
3. On the Create a new project window, enter or type console in the search box. Next, choose C# from the
Language list, and then choose Windows from the Platform list.
After you apply the language and platform filters, choose the Console App (.NET Core) template, and
then choose Next .
NOTE
If you do not see the Console App (.NET Core) template, you can install it from the Create a new project
window. In the Not finding what you're looking for? message, choose the Install more tools and features
link.
Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.
After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so,
do so. Next, choose Continue to install the workload. Then, return to step 2 in this "Create a project" procedure.
4. In the Configure your new project window, type or enter Calculator in the Project name box. Then,
choose Create .
Visual Studio opens your new project, which includes default "Hello World" code.
Notice that when you do so, the IntelliSense feature in Visual Studio offers you the option to autocomplete
the entry.
NOTE
The following animation isn't intended to duplicate the preceding code. It's intended only to show how the
autocomplete feature works.
3. Choose the green Star t button next to Calculator to build and run your program, or press F5 .
A console window opens that reveals the sum of 42 + 119, which is 161 .
4. (Optional) You can change the operator to change the result. For example, you can change the + operator
in the int c = a + b; line of code to - for subtraction, * for multiplication, or / for division. Then, when
you run the program, the result changes, too.
5. Close the console window.
Add code to create a calculator
Let's continue by adding a more complex set of calculator code to your project.
1. Delete all the code you see in the code editor.
2. Enter or paste the following new code into the code editor:
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
// Declare variables and then initialize to zero.
int num1 = 0; int num2 = 0;
3. Run your calculator app again and divide the number 42 by the number 119 .
Notice that the app now returns a decimal numeral instead of zero.
However, the app produces only a decimal result. Let's make a few more tweaks to the code so that the app can
calculate decimals too.
1. Use the Find and Replace control (Ctrl + H ) to change each instance of the float variable to double , and
to change each instance of the Convert.ToInt32 method to Convert.ToDouble .
2. Run your calculator app and divide the number 42.5 by the number 119.75 .
Notice that the app now accepts decimal values and returns a longer decimal numeral as its result.
(We'll fix the number of decimal places in the Revise the code section.)
TIP
For more information about the debugger and how it works, see the First look at the Visual Studio debugger page.
After you add the code, the section with the switch statement should look similar to the following
screenshot:
Now, when you divide any number by zero, the app will ask for another number. Even better: It won't stop asking
until you provide a number other than zero.
Fix the "format" error
If you enter an alpha character when the app expects a numeric character (or vice versa), the console app freezes.
Visual Studio then shows you what's wrong in the code editor.
To fix this error, we must refactor the code that we've previously entered.
Revise the code
Rather than rely on the program class to handle all the code, we'll divide our app into two classes: Calculator and
Program .
The Calculator class will handle the bulk of the calculation work, and the Program class will handle the user
interface and error-capturing work.
Let's get started.
1. Delete everything in the Calculator namespace between its opening and closing braces:
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput1 = Console.ReadLine();
}
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput2 = Console.ReadLine();
}
string op = Console.ReadLine();
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " +
e.Message);
}
Console.WriteLine("------------------------\n");
Code complete
During this tutorial, we've made a lot of changes to the calculator app. The app now handles computing resources
more efficiently, and it handles most user input errors.
Here's the complete code, all in one place:
using System;
namespace Calculator
{
class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such
as division, could result in an error.
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput1 = Console.ReadLine();
}
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput2 = Console.ReadLine();
}
string op = Console.ReadLine();
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " +
e.Message);
}
Console.WriteLine("------------------------\n");
Next steps
Continue with the second part of this tutorial:
Continue with Part 2
See also
C# IntelliSense
Learn to debug C# code in Visual Studio
Tutorial: Extend a simple C# console app
10/22/2020 • 7 minutes to read • Edit Online
In this tutorial, you'll learn how to use Visual Studio to extend the console app you created in the first part. You'll
learn some of the features in Visual Studio that you'll need for daily development, such as managing multiple
projects, and referencing third-party packages.
If you just completed the first part of this series, you already have the Calculator console app. To skip part 1, you
can start by opening the project from a GitHub repo. The C# Calculator app is in the vs-tutorial-samples repo, so
you can just follow the steps in Tutorial: Open a project from a repo to get started.
3. Type the project name CalculatorLibrar y , and choose Create . Visual Studio creates the new project and
adds it to the solution.
4. Instead of having Class1.cs, rename the file CalculatorLibrar y.cs . You can click on the name in Solution
Explorer to rename it, or right-click and choose Rename , or press the F2 key.
You might get asked if you want to rename any references to Class1 in the file. It doesn't matter how you
answer, since you'll be replacing the code in a future step.
5. We now have to add a project reference, so that the first project can use APIs exposed by the new class
library. Right-click on the References node in the first project and choose Add Project Reference .
The Reference Manager dialog box appears. This dialog box lets you add references to other projects, as
well assemblies and COM DLLs that your projects need.
6. In the Reference Manager dialog box, select the checkbox for the CalculatorLibrar y project, and choose
OK . The project reference appears under a Projects node in Solution Explorer .
7. In Program.cs, select the Calculator class and all its code, and press CTRL+X to cut it from Program.cs.
Then in CalculatorLibrar y , in CalculatorLibrary.cs, paste the code into the CalculatorLibrary namespace.
Then, make the Calculator class public to expose it outside the library. The code in CalculatorLibrary.cs
should now resemble the following code:
using System;
namespace CalculatorLibrary
{
public class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an
operation, such as division, could result in an error.
8. The first project has a reference, but you'll see an error that the Calculator.DoOperation call doesn't resolve.
That's because CalculatorLibrary is in a difference namespace, so add CalculatorLibrary namespace for a
fully qualified reference.
using CalculatorLibrary;
This change should let you remove the CalculatorLibrary namespace from the call site, but there's now an
ambiguity. Is Calculator the class in CalculatorLibrary, or is Calculator the namespace? To resolve the
ambiguity, rename the namespace CalculatorProgram .
namespace CalculatorProgram
using System.IO;
using System.Diagnostics;
2. Looking at how the Trace class is used, you need to hold onto a reference for the class, which is associated
with a filestream. That means, the calculator would work better as an object, so let's add a constructor.
public Calculator()
{
StreamWriter logFile = File.CreateText("calculator.log");
Trace.Listeners.Add(new TextWriterTraceListener(logFile));
Trace.AutoFlush = true;
Trace.WriteLine("Starting Calculator Log");
Trace.WriteLine(String.Format("Started {0}", System.DateTime.Now.ToString()));
}
3. And we need to change the static DoOperation method into a member method. Let's also add output to each
calculation for the log, so that DoOperation looks like the following code:
4. Now back in Program.cs, the static call is flagged with a red squiggly. To fix it, create a calculator variable
by adding the following line just before the while loop:
5. Run the program again, and when done, right-click on the project node and choose Open folder in File
Explorer , then navigate down in File Explorer to the output folder. It might be bin/Debug/netcoreapp3.1,
and open the calculator.log file.
The package is downloaded, and added to your project and a new entry appears in the References node in
Solution Explorer .
3. Add a using directive for the System.IO and Newtonsoft.Json package at the beginning of
CalculatorLibrary.cs.
using Newtonsoft.Json;
4. Now replace the constructor for Calculator with the following code, and create the JsonWriter member
object:
JsonWriter writer;
public Calculator()
{
StreamWriter logFile = File.CreateText("calculatorlog.json");
logFile.AutoFlush = true;
writer = new JsonTextWriter(logFile);
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("Operations");
writer.WriteStartArray();
}
return result;
}
6. You'll need to add a method to finish the JSON syntax once the user is done entering operation data.
8. Build and run the app, and after you're done entering a few operations, close the app properly by using the
'n' command. Now, open the calculatorlog.json file and you should see something like the following:
{
"Operations": [
{
"Operand1": 2.0,
"Operand2": 3.0,
"Operation": "Add",
"Result": 5.0
},
{
"Operand1": 3.0,
"Operand2": 4.0,
"Operation": "Multiply",
"Result": 12.0
}
]
}
Next steps
Congratulations on completing this tutorial! To learn even more, continue with the following tutorials.
Continue with more C# tutorials
Continue with Visual Studio IDE overview
See also
C# IntelliSense
Learn to debug C# code in Visual Studio
Tutorial: Get started with C# and ASP.NET Core in
Visual Studio
10/22/2020 • 10 minutes to read • Edit Online
In this tutorial for C# development with ASP.NET Core using Visual Studio, you'll create a C# ASP.NET Core web app,
make changes to it, explore some features of the IDE, and then run the app.
Create a project
First, you'll create a ASP.NET Core project. The project type comes with all the template files you'll need for a fully
functional website, before you've even added anything!
1. Open Visual Studio 2017.
2. From the top menu bar, choose File > New > Project .
3. In the New Project dialog box in the left pane, expand Visual C# , expand Web , and then choose .NET
Core . In the middle pane, choose ASP.NET Core Web Application . Then, name the file MyCoreApp and
choose OK .
Add a workload (optional)
If you don't see the ASP.NET Core Web Application project template, you can get it by adding the ASP.NET and
web development workload. You can add this workload in one of the two following ways, depending on which
Visual Studio 2017 updates are installed on your machine.
Option 1: Use the New Project dialog box
1. Select the Open Visual Studio Installer link in the left pane of the New Project dialog box. (Depending
on your display settings, you might have to scroll to see it.)
2. The Visual Studio Installer launches. Choose the ASP.NET and web development workload, and then
choose Modify .
(You might have to close Visual Studio before you can continue installing the new workload.)
Option 2: Use the Tools menu bar
1. Cancel out of the New Project dialog box. Then, from the top menu bar, choose Tools > Get Tools and
Features .
2. The Visual Studio Installer launches. Choose the ASP.NET and web development workload, and then
choose Modify .
(You might have to close Visual Studio before you can continue installing the new workload.)
Add a project template
1. In the New ASP.NET Core Web Application dialog box, choose the Web Application project template.
2. Verify that ASP.NET Core 2.1 appears in the top drop-down menu. Then, choose OK .
NOTE
If you don't see ASP.NET Core 2.1 from the top drop-down menu, make sure that you are running the most recent
release of Visual Studio. For more information about how to update your installation, see the Update Visual Studio to
the most recent release page.
Then, in the Visual Studio Installer, choose the ASP.NET and web development workload.
After that, choose the Modify button in the Visual Studio Installer. If you're prompted to save your work, do so.
Next, choose Continue to install the workload. Then, return to step 2 in this "Create a project" procedure.
3. In the Configure your new project window, type or enter MyCoreApp in the Project name box. Then,
choose Create .
4. In the Create a new ASP.NET Core Web Application window, verify that ASP.NET Core 3.0 appears in
the top drop-down menu. Then, choose Web Application , which includes example Razor Pages. Next,
choose Create .
Visual Studio opens your new project.
About your solution
This solution follows the Razor Page design pattern. It's different than the Model-View-Controller (MVC) design
pattern in that it's streamlined to include the model and controller code within the Razor Page itself.
You can put static site content—such as CSS, images, and JavaScript libraries—directly in the paths where
you want them.
7. The project also contains configuration files that manage the web app at run time. The default application
configuration is stored in appsettings.json. However, you can override these settings by using
appsettings.Development.json. Expand the appsettings.json file to view the
appsettings.Development.json file.
2. Visual Studio launches a browser window. You should then see Home , About , and Contact pages in the
menu bar. (If you don't, choose the "hamburger" menu item to view them.)
4. Return to Visual Studio, and then press Shift+F5 to stop Debug mode. This also closes the project in the
browser window.
5. In Visual Studio, choose About.cshtml . Then, delete the word additional and in its place, add the words file
and directory.
6. Choose About.cshtml.cs . Then, clean up the using directives at the top of the file by using the following
shortcut:
Choose any of the grayed-out using directives and a Quick Actions light bulb will appear just below the
caret or in the left margin. Choose the light bulb, and then choose Remove Unnecessar y Usings .
Visual Studio deletes the unnecessary using directives from the file.
7. Next, in the OnGet() method, change the body to the following code:
8. Notice that two wavy underlines appear under Environment and String . The wavy underlines appear
because these types aren't in scope.
Open the Error List toolbar to see the same errors listed there. (If you don't see the Error List toolbar,
choose View > Error List from the top menu bar.)
9. Let's fix this. In the code editor, place your cursor on either line that contains the error, and then choose the
Quick Actions light bulb in the left margin. Then, from the drop-down menu, choose using System; to add
this directive to the top of your file and resolve the errors.
10. Press Ctrl +S to save your changes, and then press F5 to open your project in the web browser.
11. At the top of the web site, choose About to view your changes.
12. Close the web browser, press Shift +F5 to stop Debug mode, and then close Visual Studio.
4. Each .cshtml file has an associated code file. To open the code file in the editor, expand the Index.cshtml
node in Solution Explorer, and choose the Index.cshtml.cs file.
You can put static site content—such as CSS, images, and JavaScript libraries—directly in the paths where
you want them.
7. The project also contains configuration files that manage the web app at run time. The default application
configuration is stored in appsettings.json. However, you can override these settings by using
appsettings.Development.json. Expand the appsettings.json file to view the
appsettings.Development.json file.
Run, debug, and make changes
1. Choose the IIS Express button in the IDE to build and run the app in Debug mode. (Alternatively, press F5 ,
or choose Debug > Star t Debugging from the menu bar.)
NOTE
If you get an error message that says Unable to connect to web ser ver 'IIS Express' , close Visual Studio and
then open it by using the Run as administrator option from the right-click or context menu. Then, run the
application again.
You might also get a message that asks if you want to accept an IIS SSL Express certificate. To view the code in a web
browser, choose Yes , and then choose Yes if you receive a follow-up security warning message.
2. Visual Studio launches a browser window. You should then see Home , and Privacy pages in the menu bar.
3. Choose Privacy from the menu bar.
The Privacy page in the browser renders the text that is set in the Privacy.cshtml file.
4. Return to Visual Studio, and then press Shift+F5 to stop Debug mode. This also closes the project in the
browser window.
5. In Visual Studio, open Privacy.cshtml for editing. Then, delete the words Use this page to detail your site's
privacy policy and in its place, add the words This page is under construction as of
@ViewData["TimeStamp"].
6. Now, let's make a code change. Choose Privacy.cshtml.cs . Then, clean up the using directives at the top
of the file by using the following shortcut:
Choose any of the grayed-out using directives and a Quick Actions light bulb will appear just below the
caret or in the left margin. Choose the light bulb, and then hover over Remove unnecessar y usings .
Choose Apply . Visual Studio deletes the unnecessary using directives from the file.
7. Next, in the OnGet() method, change the body to the following code:
8. Notice that two wavy underlines appear under DateTime . The wavy underlines appear because these type
isn't in scope.
Open the Error List toolbar to see the same errors listed there. (If you don't see the Error List toolbar,
choose View > Error List from the top menu bar.)
9. Let's fix this. In the code editor, place your cursor on either line that contains the error, and then choose the
Quick Actions light bulb in the left margin. Then, from the drop-down menu, choose using System; to add
this directive to the top of your file and resolve the errors.
12. Close the web browser, press Shift +F5 to stop Debug mode, and then close Visual Studio.
Next steps
Congratulations on completing this tutorial! We hope you learned a little bit about C#, ASP.NET Core, and the
Visual Studio IDE. To learn more about creating a web app or website with C# and ASP.NET, continue with the
following tutorials:
Create a Razor Pages web app with ASP.NET Core
See also
Publish your web app to Azure App Service by using Visual Studio
Tutorial: Create your first Universal Windows Platform
application in Visual Studio with XAML and C#
10/22/2020 • 5 minutes to read • Edit Online
In this introduction to the Visual Studio integrated development environment (IDE), you'll create a "Hello World"
app that runs on any Windows 10 device. To do so, you'll use a Universal Windows Platform (UWP) project
template, Extensible Application Markup Language (XAML), and the C# programming language.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
Create a project
First, create a Universal Windows Platform project. The project type comes with all the template files you need,
before you've even added anything!
1. Open Visual Studio.
2. From the top menu bar, choose File > New > Project .
3. In the left pane of the New Project dialog box, expand Visual C# , and then choose Windows Universal .
In the middle pane, choose Blank App (Universal Windows) . Then, name the project HelloWorld and
choose OK .
NOTE
Make sure that the location of the source project is on a New Technology File System (NTFS) formatted drive,
such as your Operating System (OS) drive. Otherwise, you might have trouble building and running your project.
NOTE
If you don't see the Blank App (Universal Windows) project template, click the Open Visual Studio Installer
link in the left pane of the New Project dialog box.
The Visual Studio Installer launches. Choose the Universal Windows Platform development workload, and then
choose Modify .
4. Accept the default Target version and Minimum version settings in the New Universal Windows
Platform Project dialog box.
1. Open Visual Studio, and on the start window, choose Create a new project .
2. On the Create a new project screen, enter Universal Windows in the search box, choose the C# template
for Blank App (Universal Windows) , and then choose Next .
NOTE
If you don't see the Blank App (Universal Windows) project template, click the Install more tools and
features link.
The Visual Studio Installer launches. Choose the Universal Windows Platform development workload, and then
choose Modify .
4. Accept the default Target version and Minimum version settings in the New Universal Windows
Platform Project dialog box.
NOTE
If this is the first time you have used Visual Studio to create a UWP app, a Settings dialog box might appear. Choose
Developer mode , and then choose Yes .
Visual Studio installs an additional Developer Mode package for you. When the package installation is complete, close the
Settings dialog box.
(If you don't see the Toolbox option, you can open it from the menu bar. To do so, choose View > Toolbar .
Or, press Ctrl +Alt +X .)
3. Click the Pin icon to dock the Toolbox window.
4. Click the Button control and then drag it onto the design canvas.
If you look at the code in the XAML Editor , you'll see that the Button has been added there, too:
(Alternatively, you can choose Debug > Star t Debugging from the menu bar or press F5 to start your
app.)
2. View your app, which appears soon after a splash screen disappears. The app should look similar to this:
(Alternatively, you can choose Debug > Star t Debugging from the menu bar or press F5 to start your
app.)
2. View your app, which appears soon after a splash screen disappears. The app should look similar to this:
Next steps
Congratulations on completing this tutorial! We hope you learned some basics about UWP and the Visual Studio
IDE. To learn more, continue with the following tutorial:
Create a user interface
See also
UWP overview
Get UWP app samples
Tutorial: Create a simple application with C#
10/22/2020 • 10 minutes to read • Edit Online
By completing this tutorial, you'll become familiar with many of the tools, dialog boxes, and designers that you can
use when you develop applications with Visual Studio. You'll create a "Hello, World" application, design the UI, add
code, and debug errors, while you learn about working in the integrated development environment (IDE).
Prerequisites
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
You can use either .NET Framework or .NET Core for this tutorial. .NET Core is the newer, more modern
framework. .NET Core requires Visual Studio 2019 version 16.3 or later.
After Visual Studio launches, you'll see tool windows, the menus and toolbars, and the main window space. Tool
windows are docked on the left and right sides of the application window, with Quick Launch , the menu bar, and
the standard toolbar at the top. In the center of the application window is the Star t Page . When you load a solution
or project, editors and designers appear in the space where the Star t Page is. When you develop an application,
you'll spend most of your time in this central area.
When you launch Visual Studio, the start window opens first. Select Continue without code to open the
development environment. You'll see tool windows, the menus and toolbars, and the main window space. Tool
windows are docked on the left and right sides of the application window, with a search box, the menu bar, and the
standard toolbar at the top. When you load a solution or project, editors and designers appear in the central space
of the application window. When you develop an application, you'll spend most of your time in this central area.
2. In the New Project dialog, select the Installed > Visual C# > Windows Desktop category, and then
select the WPF App (.NET Framework) template. Name the project HelloWPFApp , and select OK .
1. Open Visual Studio 2019.
2. On the start window, choose Create new project .
3. On the Create a new project screen, search for "WPF," choose WPF App (.NET Core) , and then choose
Next .
NOTE
You might find two WPF desktop templates, one for .NET Framework and another for .NET Core. The .NET Core
template is available in Visual Studio 2019 version 16.3 and later. You can use either one for this tutorial, but we
recommend .NET Core for new development.
4. At the next screen, give the project a name, HelloWPFApp , and choose Create .
Visual Studio creates the HelloWPFApp project and solution, and Solution Explorer shows the various files. The
WPF Designer shows a design view and a XAML view of MainWindow.xaml in a split view. You can slide the
splitter to show more or less of either view. You can choose to see only the visual view or only the XAML view.
NOTE
For more information about XAML (eXtensible Application Markup Language), see the XAML overview for WPF page.
After you create the project, you can customize it. To do so, choose Proper ties Window from the View menu, or
press F4 . Then, you can display and change options for project items, controls, and other items in an application.
The XAML markup should look something like the following example:
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="387,60,0,0" TextWrapping="Wrap" Text="TextBlock"
VerticalAlignment="Top"/>
</Grid>
The XAML markup should look something like the following example:
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="387,60,0,0" TextWrapping="Wrap" Text="Select a message
option and then choose the Display button." VerticalAlignment="Top"/>
</Grid>
2. Center the TextBlock again if you like, and then save your changes by pressing Ctrl+S or using the File
menu item.
Next, you'll add two RadioButton controls to the form.
Add radio buttons
1. In the Toolbox , find the RadioButton control.
2. Add two RadioButton controls to the design surface by choosing the RadioButton item and dragging it to
the window on the design surface. Move the buttons (by selecting them and using the arrow keys) so that
the buttons appear side by side under the TextBlock control. Use the red guidelines to align the controls.
Your window should look like this:
3. In the Proper ties window for the left RadioButton control, change the Name property (the property at the
top of the Proper ties window) to HelloButton .
4. In the Proper ties window for the right RadioButton control, change the Name property to GoodbyeButton ,
and then save your changes.
Next, you'll add display text for each RadioButton control. The following procedure updates the Content property
for a RadioButton control.
Add display text for each radio button
1. Update the Content attribute for the HelloButton and GoodbyeButton to "Hello" and "Goodbye" in the
XAML. The XAML markup should now look similar to the following example:
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a
message option and then choose the Display button." VerticalAlignment="Top"/>
<RadioButton x:Name="HelloButton" Content="Hello" HorizontalAlignment="Left" Margin="297,161,0,0"
VerticalAlignment="Top"/>
<RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left"
Margin="488,161,0,0" VerticalAlignment="Top"/>
</Grid>
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a
message option and then choose the Display button." VerticalAlignment="Top"/>
<RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left"
Margin="297,161,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left"
Margin="488,161,0,0" VerticalAlignment="Top"/>
</Grid>
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a
message option and then choose the Display button." VerticalAlignment="Top"/>
<RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left"
Margin="297,161,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left"
Margin="488,161,0,0" VerticalAlignment="Top"/>
<Button Content="Display" HorizontalAlignment="Left" Margin="377,270,0,0" VerticalAlignment="Top"
Width="75"/>
</Grid>
Start the debugger again (press F5 ). You should see the Greetings window of the application.
Now close the application window to stop debugging.
Debug with breakpoints
You can test the code during debugging by adding some breakpoints. You can add breakpoints by choosing Debug
> Toggle Breakpoint , by clicking in the left margin of the editor next to the line of code where you want the break
to occur, or by pressing F9 .
Add breakpoints
1. Open Greetings.xaml.cs, and select the following line: MessageBox.Show("Hello.")
2. Add a breakpoint from the menu by selecting Debug , then Toggle Breakpoint .
A red circle appears next to the line of code in the far left margin of the editor window.
3. Select the following line: MessageBox.Show("Goodbye.") .
4. Press the F9 key to add a breakpoint, and then press F5 to start debugging.
5. In the Greetings window, choose the Hello radio button, and then choose the Display button.
The line MessageBox.Show("Hello.") is highlighted in yellow. At the bottom of the IDE, the Autos, Locals, and
Watch windows are docked together on the left side, and the Call Stack, Breakpoints, Exception Settings,
Command, Immediate, and Output windows are docked together on the right side.
Next steps
Congratulations on completing this tutorial! To learn even more, continue with the following tutorials.
Continue with more WPF tutorials
See also
Productivity tips
Create a Windows Forms app in Visual Studio with
C#
10/22/2020 • 4 minutes to read • Edit Online
In this short introduction to the Visual Studio integrated development environment (IDE), you'll create a simple C#
application that has a Windows-based user interface (UI).
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
NOTE
Some of the screenshots in this tutorial use the dark theme. If you aren't using the dark theme but would like to, see the
Personalize the Visual Studio IDE and Editor page to learn how.
Create a project
First, you'll create a C# application project. The project type comes with all the template files you'll need, before
you've even added anything.
1. Open Visual Studio 2017.
2. From the top menu bar, choose File > New > Project .
3. In the New Project dialog box in the left pane, expand Visual C# , and then choose Windows Desktop . In
the middle pane, choose Windows Forms App (.NET Framework) . Then name the file HelloWorld .
If you don't see the Windows Forms App (.NET Framework) project template, cancel out of the New
Project dialog box and from the top menu bar, choose Tools > Get Tools and Features . The Visual Studio
Installer launches. Choose the .NET desktop development workload, then choose Modify .
Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.
After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so,
do so. Next, choose Continue to install the workload. Then, return to step 2 in this "Create a project" procedure.
4. In the Configure your new project window, type or enter HelloWorld in the Project name box. Then,
choose Create .
3. Choose the Button control and then drag it onto the form.
4. In the Proper ties window, locate Text , change the name from Button1 to Click this , and then press
Enter .
(If you don't see the Proper ties window, you can open it from the menu bar. To do so, choose View >
Proper ties Window . Or, press F4 .)
5. In the Design section of the Proper ties window, change the name from Button1 to btnClickThis , and
then press Enter .
NOTE
If you've alphabetized the list in the Proper ties window, Button1 appears in the (DataBindings) section, instead.
Several things will happen. In the Visual Studio IDE, the Diagnostics Tools window will open, and an
Output window will open, too. But outside of the IDE, a Form1 dialog box appears. It will include your Click
this button and text that says Label1 .
2. Choose the Click this button in the Form1 dialog box. Notice that the Label1 text changes to Hello
World! .
Next steps
To learn more, continue with the following tutorial:
Tutorial: Create a picture viewer
See also
More C# tutorials
Visual Basic tutorials
C++ tutorials
Tutorial: Create your first ASP.NET Core App using
Entity Framework with Visual Studio 2019
10/22/2020 • 2 minutes to read • Edit Online
In this tutorial, you'll create an ASP.NET Core web app that uses data, and deploy it to Azure. This tutorial consists of
the following steps:
Step 1: Install Visual Studio 2019
Step 2: Create your first ASP.NET Core web app
Step 3: Work with data using Entity Framework
Step 4: Expose a web API from your ASP.NET Core app
Step 5: Deploy your ASP.NET Core app to Azure
Install
Click Install and let the installer download and install Visual Studio.
See also
Tutorial: Get started with C# and ASP.NET Core A more detailed tutorial without a video walkthrough
Step 2: Create your first ASP.NET Core web app
10/22/2020 • 3 minutes to read • Edit Online
Create your first ASP.NET Core Web App with this video tutorial and step-by-step instructions.
Watch this video and follow along to create your first ASP.NET Core app.
WARNING
Make sure you choose ASP .NET Core 2.1 or ASP.NET Core 2.2. This tutorial is not compatible with ASP.NET Core 3.x.
Run the application again. You should see that the page now displays the current time, but it's always midnight!
That's not right.
You should now see the actual server time in the browser when you navigate to the app.
NOTE
Your output might differ from the image, since the output format of ToShortDateTimeString depends on the current culture
setting. See ToShortTimeString().
Next steps
In the next video, you'll learn how to add data support to your app.
Tutorial: Working with Data in Your ASP.NET Core App
See also
Tutorial: Create a Razor Pages web app with ASP.NET Core
Step 3: Work with data using Entity Framework
10/22/2020 • 3 minutes to read • Edit Online
Follow these steps to start working with data using Entity Framework Core in your ASP.NET Core Web App.
Watch this video and follow along to add data to your first ASP.NET Core app.
In addition to adding pages in the Games folder, the scaffolding operation added code to my Startup.cs class.
Looking in the ConfigureServices method in this class you will see this code has been added:
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
You'll also find the AppDbContext connection string has been added to the project's appsettings.json file.
If you run the app now, it may fail because no database has been created, yet. You can configure the app to
automatically create the database if needed by adding some code to Program.cs:
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
try
{
var context = services.GetRequiredService<Data.AppDbContext>();
context.Database.EnsureCreated();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
host.Run();
}
To resolve the typenames in the preceding code, add the following using statements to Program.cs at the end of
the existing block of using statements:
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Models;
Test it out
Run the application and navigate to /Games in the address bar. You will see an empty list page. Click Create New
to add a new Game to the collection. Fill in the form and click Create . You should see it in the list view. Click on
Details to see the details of a single record.
Add another record. You can click Edit to change the details of a record, or Delete to remove it, which will prompt
you to confirm before it actually deletes the record.
That's all it took to start working with data in an ASP.NET Core app using EF Core and Visual Studio 2019.
Next steps
In the next video, you'll learn how to add web API support to your app.
Step 4: Exposing a web API From Your ASP.NET Core App
See also
Razor Pages with Entity Framework Core in ASP.NET Core
ASP.NET Core Razor Pages with EF Core
Step 4: Expose a web API from your ASP.NET Core
app
10/22/2020 • 4 minutes to read • Edit Online
Follow these steps to add a web API to your existing ASP.NET Core app.
Watch this video and follow along to add web API support to your first ASP.NET Core app.
The first one specifies the route for actions in this controller as being api/[controller] which means if the
controller is named GamesController the route will be api/Games .
The second attribute, [ApiController] , adds some useful validations to the class, such as ensuring every action
method includes its own [Route] attribute.
The controller uses the existing AppDbContext , passed into its constructor. Each action will use this field to work
with the application's data.
// GET: api/Games
[HttpGet]
public IEnumerable<Game> GetGame()
{
return _context.Game;
}
The first method is a simple GET request, as specified using the [HttpGet] attribute. It takes no parameters and
returns a list of all games in the database.
// GET: api/Games/5
[HttpGet("{id}")]
public async Task<IActionResult> GetGame([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (game == null)
{
return NotFound();
}
return Ok(game);
}
The next method specifies {id} in the route, which will be added to the route following a / so the full route will
be something like api/Games/5 as shown in the comment at the top. The id input is mapped to the id
parameter on the method. Inside the method, if the model is invalid, a BadRequest result is returned. Otherwise, EF
will attempt to find the record matching the provided id . If it can't a NotFound result is returned, otherwise the
appropriate Game record is returned.
// PUT: api/Games/5
[HttpPut("{id}")]
public async Task<IActionResult> PutGame([FromRoute] int id, [FromBody] Game game)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != game.Id)
{
return BadRequest();
}
_context.Entry(game).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!GameExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
Next, an [HttpPut] request made to the API is used to perform updates. The new Game record is provided in the
body of the request. Some validation and error checking is performed, and if everything is successful the record in
the database is updated with the values provided in the body of the request. Otherwise an appropriate error
response is returned.
// POST: api/Games
[HttpPost]
public async Task<IActionResult> PostGame([FromBody] Game game)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Game.Add(game);
await _context.SaveChangesAsync();
An [HttpPost] request is used to add new records to the system. As with the [HttpPut] , the record is added in
the body of the request. If it's valid, EF Core adds the record to the database and the action returns the updated
record (with its database generated ID) and a link to the record in the API.
// DELETE: api/Games/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteGame([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Game.Remove(game);
await _context.SaveChangesAsync();
return Ok(game);
}
Finally, an [HttpDelete] route is used with an ID to delete a record. If the request is valid and a record with the
given ID exists, EF Core delete it from the database.
Adding Swagger
Swagger is an API documentation and testing tool that can be added as a set of services and middleware to an
ASP.NET Core app. To do so, right-click on the project and choose Manage NuGet Packages . Then, click Browse ,
search for Swashbuckle.AspNetCore , and install the 4.0.1 version.
Once installed, open Startup.cs and add the following to the end of the ConfigureServices method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
You'll also need to add using Swashbuckle.AspNetCore.Swagger; at the top of the file.
Next, add the following to the Configure method, just before UseMvc :
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
Now you should be able to build and run your app. In the browser, navigate to /swagger in the address bar. You
should see a list of your app's API endpoints and models.
Click an endpoint under Games, then Try it out and Execute to see how the different endpoints behave.
Next steps
In the next video, you'll learn how to deploy your app to Azure.
Step 5: Deploying Your ASP.NET Core App to Azure
See also
Getting Started with Swashbuckle and ASP.NET Core
ASP.NET Core web API help pages with Swagger / OpenAPI
Step 5: Deploy your ASP.NET Core app to Azure
10/22/2020 • 3 minutes to read • Edit Online
Follow these steps to deploy your ASP.NET Core app and its database to Azure.
Watch this video and follow along to deploy your first ASP.NET Core app to Azure.
2. For the specific target, choose Azure App Ser vice (Windows) .
3. Choose Create a new Azure App Ser vice . If you don't already have an Azure account, click the Create
your Free Azure Account and complete the brief registration process.
4. Specify a name and resource group, or accept the default values, and choose Create . A resource group is
just a way of organizing related resources in Azure, such as services that work together with storage
accounts, key vaults, and databases.
5. Choose Finish . The resources are created in Azure, the app is deployed, and the Publish tab is populated
with the information about what you just created. The Publish tab provides a button to publish with one
click with the same configuration, shows configuration details, or lets you add services such as a database.
Now, add an Azure SQL Server database.
1. On the Publish tab, under Ser vice Dependencies , next to SQL Ser ver database , choose Configure .
2. On the next screen, choose Azure SQL Database .
3. On the Configure SQL Database screen, choose Create a SQL Database .
4. On the Azure SQL Database: Create new screen, create a new database server.
5. On the SQL Ser ver : Create new screen, choose a name, location, and specify an administrator username
and password.
Exploring the Azure portal and your hosted app
Once the app service is created your site will launch in a browser. While it's loading you can also find the App
Service in the Azure portal. Exploring the available options for your app service you'll find an Over view section
where you can start and stop the app.
Scalability
You can examine the options to scale the app up as well as out. Scaling up refers to increasing the resources given
to each instance hosting your app. Scaling out refers to increasing the number of instances hosting your app. You
can configure autoscale for your app, which will automatically increase the number of instances used to host your
app in response to load,and then reduce them once the load has decreased.
Security and compliance
Another benefit of hosting our app using Azure is security and compliance. Azure App Service provides ISO, SOC,
and PCI compliance. We can choose to authenticate users with Azure Active Directory or social logins like Twitter,
Facebook, Google,or Microsoft. We can create IP restrictions, manage service identities, add custom domains, and
support SSL for the app, as well as configure backups with restorable archive copies of the app’s content,
configuration, and database. These features are accessed in the Authentication / Authorization, Identity, backups,
and SSL Settings menu options.
Deployment slots
Frequently when you deploy an app, there’s a small period of downtime while the app restarts. Deployment Slots
avoid this issue by allowing you to deploy to a separate staging instance or set of instances and warm these up
before swapping them into production. The swap is just an instant and seamless traffic redirection. If there are any
issues in production after the swap, you can always swap back to your last known good production state.
Next steps
Learn more about how to architect ASP.NET Core applications with these free resources.
ASP.NET Core Application Architecture
See also
Publish an ASP.NET Core app to Azure with Visual Studio
How to: Run a C# program in Visual Studio
4/20/2020 • 6 minutes to read • Edit Online
What you need to do to run a program depends on what you're starting from, what type of program, app, or
service it is, and whether you want to run it under the debugger or not. In the simplest case, when you have a
project open in Visual Studio, build and run it by pressing Ctrl +F5 (Star t without debugging ) or F5 (Star t with
debugging ), or press the green arrow (Star t Button ) on the main Visual Studio toolbar.
Troubleshooting
Your code might have errors, but if the code is correct, but just depends on some other assemblies or NuGet
packages, or was written to target a different version of .NET, you might be able to easily fix it.
Add references
To build properly, the code must be correct and have the right references set up to libraries or other dependencies.
You can look at the red squiggly lines and at the Error List to see if the program has any errors, even before you
compile and run it. If you're seeing errors related to unresolved names, you probably need to add a reference or a
using directive, or both. If the code references any assemblies or NuGet packages, you need to add those references
in the project.
Visual Studio tries to help you identify missing references. When a name is unresolved, a light bulb icon appears in
the editor. If you click the light bulb, you can see some suggestions on how to fix the issue. Fixes might be to:
add a using directive
add a reference to an assembly, or
install a NuGet package.
Missing using directive
For example, in the following screen, you can choose to add using System; to the start of the code file to resolve
the unresolved name Console :
If that doesn't solve the issue and Visual Studio can't locate the package, try searching for it online. See Install and
use a NuGet package in Visual Studio.
Next steps
Explore the Visual Studio development environment by reading Welcome to the Visual Studio IDE.
See also
Create your first C# app
Tutorial: Open a project from a repo
10/22/2020 • 3 minutes to read • Edit Online
In this tutorial, you'll use Visual Studio to connect to a repository for the first time and then open a project from it.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
4. In the box that says Enter the URL of a Git repo to clone , type or paste the URL for your repo, and then
press Enter . (You might receive a prompt to sign in to GitHub; if so, do so.)
After Visual Studio clones your repo, Team Explorer closes and Solution Explorer opens. A message appears
that says Click on Solutions and Folders above to view a list of Solutions. Choose Solutions and Folders .
5. If you have a solution file available, it will appear in the "Solutions and Folders" fly-out menu. Choose it, and
Visual Studio opens your solution.
If you do not have a solution file (specifically, a .sln file) in your repo, the fly-out menu will say "No Solutions
Found." However, you can double-click any file from the folder menu to open it in the Visual Studio code
editor.
Review your work
View the following animation to check the work that you completed in the previous section.
1. Open Visual Studio 2019.
2. On the start window, choose Clone or check out code .
If you do not have a solution file (specifically, a .sln file) in your repo, the fly-out menu will say "No Solutions
Found." However, you can double-click any file from the folder menu to open it in the Visual Studio code
editor.
NOTE
What you see in the list box depends on the Azure DevOps repositories that you have access to.
5. After Visual Studio clones your repo, Team Explorer closes and Solution Explorer opens. A message appears
that says Click on Solutions and Folders above to view a list of Solutions. Choose Solutions and Folders .
A solution file (specifically, a .sln file), will appear in the "Solutions and Folders" fly-out menu. Choose it, and
Visual Studio opens your solution.
If you do not have a solution file in your repo, the fly-out menu will say "No Solutions Found". However, you
can double-click any file from the folder menu to open it in the Visual Studio code editor.
1. Open Visual Studio 2019.
2. On the start window, choose Clone or check out code .
Visual Studio opens Team Explorer and a notification appears when the clone is complete.
5. To view your folders and files, choose the Show Folder View link.
If you do not have a solution file in your repo, a "No Solutions Found" message appears. However, you can
double-click any file from the folder menu to open it in the Visual Studio code editor.
Next steps
If you're ready to code with Visual Studio, dive into any of the following language-specific tutorials:
Visual Studio tutorials | C#
Visual Studio tutorials | Visual Basic
Visual Studio tutorials | C++
Visual Studio tutorials | Python
Visual Studio tutorials | JavaScript , TypeScript , and Node.js
See also
Azure DevOps Services: Get started with Azure Repos and Visual Studio
Microsoft Learn: Get started with Azure DevOps
Learn to use the code editor with C#
10/22/2020 • 6 minutes to read • Edit Online
In this 10-minute introduction to the code editor in Visual Studio, we'll add code to a file to look at some of the
ways that Visual Studio makes writing, navigating, and understanding C# code easier.
TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
This article assumes you're already familiar with C#. If you aren't, we suggest you look at a tutorial such as Get
started with C# and ASP.NET Core in Visual Studio first.
TIP
To follow along with this article, make sure you have the C# settings selected for Visual Studio. For information about
selecting settings for the integrated development environment (IDE), see Select environment settings.
The list includes snippets for creating a class, a constructor, a for loop, an if or switch statement, and more.
Comment out code
The toolbar, which is the row of buttons under the menu bar in Visual Studio, can help make you more productive
as you code. For example, you can toggle IntelliSense completion mode (IntelliSense is a coding aid that displays a
list of matching methods, amongst other things), increase or decrease a line indent, or comment out code that you
don't want to compile. In this section, we'll comment out some code.
string[] morewords = {
"over",
"the",
"lazy",
"dog"
};
2. We're not using the morewords variable, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing semi-colon,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .
The C# comment characters // are added to the beginning of each selected line to comment out the code.
The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again, click
the same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called Outlining
and is especially useful when you're collapsing long methods or entire classes.
View symbol definitions
The Visual Studio editor makes it easy to inspect the definition of a type, method, etc. One way is to navigate to the
file that contains the definition, for example by choosing Go to Definition or pressing F12 anywhere the symbol
is referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use
Peek Definition. Let's peek at the definition of the string type.
1. Right-click on any occurrence of string and choose Peek Definition from the content menu. Or, press
Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up window,
or even peek at the definition of another type from the peeked code.
2. Close the peeked definition window by choosing the small box with an "x" at the top right of the pop-up
window.
You see IntelliSense show you Quick Info about the query symbol.
2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code. You can even practice using code snippets again by
entering cw and then pressing Tab twice to generate the Console.WriteLine code.
3. Press Enter .
Both occurrences of words have been renamed, as well as the reference to words in the code comment.
Next steps
Learn about projects and solutions
See also
Code snippets
Navigate code
Outlining
Go To Definition and Peek Definition
Refactoring
Use IntelliSense
Compile and build in Visual Studio
10/22/2020 • 2 minutes to read • Edit Online
For a first introduction to building within the IDE, see Walkthrough: Building an application.
You can use any of the following methods to build an application: the Visual Studio IDE, the MSBuild command-line
tools, and Azure Pipelines:
B UIL D M ET H O D B EN EF IT S
The documentation in this section goes into further details of the IDE-based build process. For more information on
the other methods, see MSBuild and Azure Pipelines, respectively.
NOTE
This topic applies to Visual Studio on Windows. For Visual Studio for Mac, see Compile and build in Visual Studio for Mac.
See also
Building (compiling) website projects
Compile and build (Visual Studio for Mac)
CMake projects in Visual Studio
Tutorial: Learn to debug C# code using Visual Studio
4/25/2020 • 11 minutes to read • Edit Online
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 are running your application with the debugger attached. When you do this, 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 is the first time that you've
tried to debug code, you may 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# does not support Edit-and-continue. F# and JavaScript do not
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
You must have Visual Studio 2019 installed and the .NET Core cross-platform development workload.
You must have Visual Studio 2017 installed and the .NET Core cross-platform development workload.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features..., which
opens the Visual Studio Installer. The Visual Studio Installer launches. Choose the .NET Core cross-platform
development workload, then choose Modify .
Create a project
First, you'll create a .NET Core console application project. The project type comes with all the template files you'll
need, before you've even added anything!
1. Open Visual Studio 2017.
2. From the top menu bar, choose File > New > Project .
3. In the New Project dialog box in the left pane, expand C# , and then choose .NET Core . In the middle pane,
choose Console App (.NET Core) . Then name the project get-started-debugging.
If you don't see the Console App (.NET Core) project template, choose the Open Visual Studio
Installer link in the left pane of the New Project dialog box.
The Visual Studio Installer launches. Choose the .NET Core cross-platform development workload, and
then choose Modify .
1. Open Visual Studio 2019.
If the start window is not open, choose File > Star t Window .
2. On the start window, choose Create a new project .
3. On the Create a new project window, enter or type console in the search box. Next, choose C# from the
Language list, and then choose Windows from the Platform list.
After you apply the language and platform filters, choose the Console App (.NET Core) template, and
then choose Next .
NOTE
If you do not see the Console App (.NET Core) template, you can install it from the Create a new project
window. In the Not finding what you're looking for? message, choose the Install more tools and features
link. Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.
4. In the Configure your new project window, type or enter GetStartedDebugging in the Project name
box. Then, choose Create .
Visual Studio opens your new project.
Hello, f! Count to 1
Hello, fr! Count to 2
Hello, fre! Count to 3
Hello, fred! Count to 4
Hello, fred ! Count to 5
Hello, fred s! Count to 6
Hello, fred sm! Count to 7
Hello, fred smi! Count to 8
Hello, fred smit! Count to 9
Hello, fred smith! Count to 10
In this tutorial, we'll take a closer look at this app using the debugger and get a look at the debugger
features.
2. Stop the debugger by pressing the red stop button (Shift + F5 ).
3. In the console window, press a key to close the console window.
The yellow arrow represents the statement on which the debugger paused, which also suspends app
execution at the same point (this statement has not yet executed).
If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. Otherwise, F5
continues running the app to the next breakpoint.
Breakpoints are a useful feature when you know the line of code or the section of code that you want to
examine in detail. For information on the different types of breakpoints you can set, such as conditional
breakpoints, see Using breakpoints.
The value of the variable changes with each iteration of the for loop, showing values of f , then fr , then
fre , and so on. To advance the debugger through the loop faster in this scenario, you can press F5 (or
choose Debug > Continue ) instead, which advances you to the breakpoint instead of the next statement.
Often, when debugging, you want a quick way to check property values on variables, to see whether they
are storing the values that you expect them to store, and the data tips are a good way to do it.
6. While still paused in the for loop in the Main method, press F11 (or choose Debug > Step Into ) until
you pause at the SendMessage method call.
You should be at this line of code:
SendMessage(name, a[i]);
7. Press F11 one more time to step into the SendMessage method.
The yellow pointer advances into the SendMessage method.
F11 is the Step Into command and advances the app execution one statement at a time. F11 is a good way
to examine the execution flow in the most detail. By default, the debugger skips over non-user code (if you
want more details, see Just My Code).
Let's say that you are done examining the SendMessage method, and you want to get out of the method but
stay in the debugger. You can do this using the Step Out command.
8. Press Shift + F11 (or Debug > Step Out ).
This command resumes app execution (and advances the debugger) until the current method or function
returns.
You should be back in the for loop in the Main method, paused at the SendMessage method call. For more
information on different ways to move through your code, see Navigate code in the debugger.
NOTE
The Run to Click button is new in Visual Studio 2017. (If you don't see the green arrow button, use F11 in this
example instead to advance the debugger to the right place.)
The Locals window shows you the variables that are in the current scope, that is, the current execution
context.
Set a watch
1. In the main code editor window, right-click the name variable and choose Add Watch .
The Watch window opens at the bottom of the code editor. You can use a Watch window to specify a
variable (or an expression) that you want to keep an eye on.
Now, you have a watch set on the name variable, and you can see its value change as you move through the
debugger. Unlike the other variable windows, the Watch window always shows the variables that you are
watching (they're grayed out when out of scope).
Examine the call stack
1. While paused in the for loop, click the Call Stack window, which is by default open in the lower right
pane.
If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack .
2. Click F11 a few times until you see the debugger pause in the SendMessage method. Look at the Call Stack
window.
The Call Stack window shows the order in which methods and functions are getting called. The top line
shows the current function (the SendMessage method in this app). The second line shows that SendMessage
was called from the Main method, and so on.
NOTE
The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.
The call stack is a good way to examine and understand the execution flow of an app.
You can double-click a line of code to go look at that source code and that also changes the current scope
being inspected by the debugger. This action does not advance the debugger.
You can also use right-click menus from the Call Stack window to do other things. For example, you can
insert breakpoints into specified functions, advance the debugger using Run to Cursor , and go examine
source code. For more information, see How to: Examine the Call Stack.
WARNING
Often you need to be careful with this feature, and you see a warning in the tooltip. You may see other warnings,
too. Moving the pointer cannot revert your application to an earlier app state.
Next steps
In this tutorial, you've learned how to start the debugger, step through code, and inspect variables. You may want
to get a high-level look at debugger features along with links to more information.
First look at the debugger
Get started with unit testing
4/25/2020 • 4 minutes to read • Edit Online
Use Visual Studio to define and run unit tests to maintain code health, ensure code coverage, and find errors and
faults before your customers do. Run your unit tests frequently to make sure your code is working properly.
namespace HelloWorldCore
2. In Solution Explorer , select the solution node. Then, from the top menu bar, select File > Add > New
Project .
3. In the new project dialog box, find a unit test project template for the test framework you want to use and
select it.
Click Next , choose a name for the test project, and then click Create .
4. In the unit test project, add a reference to the project you want to test by right-clicking on References or
Dependencies and then choosing Add Reference .
5. Select the project that contains the code you'll test and click OK .
namespace HelloWorldTests
{
[TestClass]
public class UnitTest1
{
private const string Expected = "Hello World!";
[TestMethod]
public void TestMethod1()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw);
HelloWorldCore.Program.Main();
Or, for an NUnit project, you might use the following code.
using NUnit.Framework;
using System.IO;
using System;
namespace HelloWorldTests
{
public class Tests
{
private const string Expected = "Hello World!";
[SetUp]
public void Setup()
{
}
[Test]
public void TestMethod1()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw);
HelloWorldCore.Program.Main();
TIP
For more details about creating unit tests, see Create and run unit tests for managed code.
After the tests have completed, a green check mark indicates that a test passed. A red "x" icon indicates that a
test failed.
TIP
You can use Test Explorer to run unit tests from the built-in test framework (MSTest) or from third-party test frameworks. You
can group tests into categories, filter the test list, and create, save, and run playlists of tests. You can also debug tests and
analyze test performance and code coverage.
1. Turn live unit testing from the Test menu by choosing Test > Live Unit Testing > Star t .
2. View the results of the tests within the code editor window as you write and edit code.
3. Click a test result indicator to see more information, such as the names of the tests that cover that method.
For more information about live unit testing, see Live unit testing.
TIP
IntelliTest is only available for managed code that targets the .NET Framework.
4. Add a reference from the test project to the project that contains the code you want to test.
Right-click on the project in Solution Explorer , and then select Add > Reference . (You can also add a
reference from the right-click menu of the References or Dependencies node.)
5. Add code to your test method.
6. Run the test from Test Explorer or by right-clicking on the test code and choosing Run Test(s) .
See also
Walkthrough: Create and run unit tests for managed code
Create Unit Tests command
Generate tests with IntelliTest
Run tests with Test Explorer
Analyze code coverage
Create a database and add tables in Visual Studio
10/22/2020 • 5 minutes to read • Edit Online
You can use Visual Studio to create and update a local database file in SQL Server Express LocalDB. You can also
create a database by executing Transact-SQL statements in the SQL Ser ver Object Explorer tool window in
Visual Studio. In this topic, we'll create an .mdf file and add tables and keys by using the Table Designer.
Prerequisites
To complete this walkthrough, you'll need the .NET desktop development and Data storage and processing
workloads installed in Visual Studio. To install them, open Visual Studio Installer and choose Modify (or More >
Modify ) next to the version of Visual Studio you want to modify.
NOTE
The procedures in this article apply only to .NET Framework Windows Forms projects, not to .NET Core Windows Forms
projects.
TIP
If you can't expand the Data Connections node, or the SampleDatabase.mdf connection is not listed, select the
Connect to Database button in the Server Explorer toolbar. In the Add Connection dialog box, make sure that
Microsoft SQL Ser ver Database File is selected under Data source , and then browse to and select the
SampleDatabase.mdf file. Finish adding the connection by selecting OK .
C O L UM N N A M E DATA T Y P E A L LO W N UL L S
4. Right-click on the CustomerID row, and then select Set Primar y Key .
5. Right-click on the default row ( Id ), and then select Delete .
6. Name the Customers table by updating the first line in the script pane to match the following sample:
C O L UM N N A M E DATA T Y P E A L LO W N UL L S
2. Set OrderID as the primary key, and then delete the default row.
3. Name the Orders table by updating the first line in the script pane to match the following sample:
2. In the text box that appears, replace the text ToTable with Customers .
3. In the T-SQL pane, update the last line to match the following sample:
IMPORTANT
Make sure that all order IDs and order quantities are integers and that each customer ID matches a value that you
specified in the CustomerID column of the Customers table.
See also
Accessing data in Visual Studio