Visualstudio Get Started Csharp Vs 2022
Visualstudio Get Started Csharp Vs 2022
Visualstudio Get Started Csharp Vs 2022
Get started
c HOW-TO GUIDE
b GET STARTED
f QUICKSTART
Create C# apps
g TUTORIAL
g TUTORIAL
Run a program
c HOW-TO GUIDE
Access data
Welcome to the Visual Studio IDE | C#
Article • 03/10/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
The preceding image shows Visual Studio with an open project that shows key windows
and their functionality:
In Solution Explorer, at upper right, you can view, navigate, and manage your code
files. Solution Explorer can help organize your code by grouping the files into
solutions and projects.
The central editor window, where you'll probably spend most of your time, displays
file contents. In the editor window, you can edit code or design a user interface
such as a window with buttons and text boxes.
In Git Changes at lower right, you can track work items and share code with others
by using version control technologies like Git and GitHub .
Editions
Visual Studio is available for Windows and Mac. Visual Studio for Mac has many of the
same features as Visual Studio for Windows, and is optimized for developing cross-
platform and mobile apps. This article focuses on the Windows version of Visual Studio.
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.
Squiggles are wavy underlines that alert you to errors or potential problems in
your code as you type. These visual clues help you fix problems immediately,
without waiting to discover errors during build or runtime. If you hover over a
squiggle, you see more information about the error. A lightbulb might also appear
in the left margin showing Quick Actions you can take to fix the error.
Code Cleanup
With the click of a button, you can format your code and apply any code fixes
suggested by your code style settings, .editorconfig conventions, and Roslyn
analyzers. Code Cleanup, currently available for C# code only, helps you resolve
issues in your code before it goes to code review.
Refactoring
IntelliSense
IntelliSense is a set of features that display 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, so you don't have to look up type information
elsewhere.
The following illustration shows how IntelliSense displays a member list for a type:
Visual Studio menus, options, and properties can seem overwhelming at times.
Visual Studio search, or Ctrl+Q, is a great way to rapidly find IDE features and code
in one place.
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 your app type
or programming language. You can instantly and securely share your project. You
can also share 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
information can be useful 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 code references, code changes, linked bugs, work items,
code reviews, and unit tests, without leaving the editor.
Go To Definition
The Peek Definition window shows a method or type definition without opening a
separate file.
Hot Reload
Hot Reload enables you to edit your application's code files and apply the code
changes immediately to the running application.
To get started, download Visual Studio and install it on your system. In the modular
installer, you choose and install workloads, which are groups of features you need for
the programming languages or platforms you want. To use the following steps to create
a program, be sure to select the .NET desktop development workload during
installation.
When you open Visual Studio for the first time, you can sign in by using your Microsoft
account or your work or school account.
Create a program
Dive in and create a simple program.
1. Start Visual Studio. The start window appears with options for cloning a repo,
opening a recent project, or creating a new project.
3. To find a template, you can type or enter keywords in the search box. The list of
available templates filters based on the keywords you enter. You can further filter
the template results by choosing C# from the All languages dropdown list,
Windows from the All platforms list, and Console from the All project types list.
5. In the Additional information window, verify that .NET 6.0 appears in the Target
Framework drop-down menu, and then select Create.
Visual Studio creates the project. The program is a simple "Hello World"
application that calls the Console.WriteLine() method to display the string Hello,
World! in a console window.
The project files appear on the right side of the Visual Studio IDE, in a window
called the Solution Explorer. In the Solution Explorer window, select the
Program.cs file. The C# code for your app opens in the central editor window,
which takes up most of the space.
Small, vertical dashed lines in the code indicate which braces match one another.
You can also choose small, boxed minus or plus signs to collapse or expand blocks
of code. This code outlining feature lets you hide code you don't need to see,
helping to minimize onscreen clutter.
Many other menus and tool windows are available.
6. Start the app by choosing Debug > Start Without Debugging from the Visual
Studio top menu. 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!
8. Let's add some more code to the app. Add the following C# code before the line
that says Console.WriteLine("Hello World!"); :
C#
This code displays What is your name? in the console window, and then waits until
the user enters some text.
C#
Console.WriteLine($"\nHello {name}!");
10. Run the app again by selecting Debug > Start Without Debugging or pressing
Ctrl+F5.
Visual Studio rebuilds the app, and a console window opens and prompts you for
your name.
11. Type your name in the console window and press Enter.
12. Press any key to close the console window and stop the running program.
1. Double-click the name variable, and type the new name for the variable, username.
A box appears around the variable, and a light bulb appears in the margin.
2. 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.
A box displays the members of the DateTime class. The description of the currently
selected member also displays in a separate box.
4. Select the member named Now, which is a property of the class, by double-
clicking it or pressing Tab. Complete the line of code by adding a semicolon to the
end of the line: DateTime now = DateTime.Now; .
C#
Tip
6. Next, use refactoring again to make the code a little more concise. Select the
variable now in the line DateTime now = DateTime.Now; . A screwdriver icon appears
in the margin on that line.
7. Select the screwdriver icon to see available suggestions from Visual Studio. This
case shows the Inline temporary variable refactoring to remove a line of code
without changing the overall code behavior.
8. Select Inline temporary variable to refactor the code.
9. Run the program again by pressing Ctrl+F5. The output looks something like this:
Debug code
When you write code, you should 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, and
observe how the variable value changes as the code runs.
Set a breakpoint to see the value of the username variable while the program is running.
3. When the console window appears and asks for your name, enter your name.
The focus returns to the Visual Studio code editor, and the line of code with the
breakpoint is highlighted in yellow. The yellow highlight means that this line of
code will execute next. The breakpoint makes the app pause execution at this line.
4. Hover your mouse over the username variable to see its value. You can also right-
click on username and select Add Watch to add the variable to the Watch window,
where you can also see its value.
Once the app is running, you can apply code changes to the running app by clicking the
Hot Reload button.
For more information about debugging in Visual Studio, see the Debugger feature tour.
1. On the menu bar, choose Tools > Options to open the Options dialog.
2. On the Environment > General options page, change the Color Theme selection
to Blue or Light, and then select OK.
The color theme for the entire IDE changes accordingly. The following screenshot
shows the Blue theme:
To learn about other ways you can personalize the IDE, see Personalize Visual Studio.
1. On the menu bar, choose Tools > Import and Export Settings.
2. In the Import and Export Settings Wizard, select Reset all settings, and then
select Next.
3. On the Save Current Settings page, choose whether to save your current settings
before resetting. If you haven't customized any settings, select No, just reset
settings, overwriting my current settings. Then select Next.
4. On the Choose a Default Collection of Settings page, choose Visual C#, and then
select Finish.
Next steps
Explore Visual Studio further by following along with one of these introductory articles:
See also
Discover more Visual Studio features.
Visit visualstudio.microsoft.com .
Read the Visual Studio blog .
Learn to use the code editor with C#
Article • 09/01/2022
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
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.
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.
1. Open Visual Studio. Press Esc, or choose Continue without code on the start
window, to open the development environment.
2. From the File menu on the menu bar, choose New > File, or press Ctrl+N.
3. In the New File dialog box, under the General category, choose Visual C# Class,
and then choose Open.
A new file opens in the editor with the skeleton of a C# class. You don't have to
create a full Visual Studio project to gain some of the benefits that the code editor
offers—all you need is a code file.
Use code snippets
Visual Studio provides useful code snippets that you can use to quickly and easily
generate commonly used code blocks. Code snippets are available for different
programming languages including C#, Visual Basic, and C++.
1. Place your cursor just above the final closing brace } in the file, and type the
characters svm . svm stands for static void Main —don't worry if you don't know
what that means yet.
A pop-up dialog box appears with information about the svm code snippet.
Available code snippets vary for different programming languages. You can look at the
available code snippets for your language by choosing Edit > IntelliSense > Insert
Snippet or pressing Ctrl+K, Ctrl+X, and then choosing the folder for your programming
language. For C#, the snippet list looks like this:
The list includes snippets for creating a class, a constructor, a for loop, an if or switch
statement, and more.
C#
// someWords is a string array.
string[] someWords = {
"the",
"quick",
"brown",
"fox",
"jumps"
};
string[] moreWords = {
"over",
"the",
"lazy",
"dog"
};
2. We're not using the moreWords variable, but we might use it later so we don't want
to delete it. Instead, we'll comment out those lines. Select the entire definition of
moreWords down to the closing semicolon, and then choose the Comment out the
selected lines button on the toolbar. If you prefer to use the keyboard, press
Ctrl+E, Ctrl+C.
The C# comment characters // are added to the beginning of each selected line
to comment out the code.
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 peek definition window by choosing the small box with an "x" at the top
right of the pop-up window.
Let's add a line of code to print out the ordered strings to the console window, which is
the standard place for output from the program to go.
C#
You'll see an IntelliSense pop-up appear with information about the query symbol.
2. To insert the rest of the word query by using IntelliSense word completion, press
Tab.
3. Finish off the code block to look like the following code. You can practice further
with code snippets by entering cw and then pressing Tab twice to generate the
Console.WriteLine statement.
C#
Refactor a name
Nobody gets code right the first time, and one of the things you might have to change
is the name of a variable or method. Let's try out Visual Studio's refactor functionality to
rename the someWords variable to unsortedWords .
1. Place your cursor over the definition of the someWords variable, and choose
Rename from the right-click or context menu, or press F2.
2. Enter the desired name unsortedWords. You'll see that the reference to
unsortedWords in the query assignment statement is also automatically renamed.
Before you press Enter, select the Include comments checkbox in the Rename
pop-up box.
Both occurrences of someWords in your code have been renamed, as well as the
text someWords in your 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
Introduction to projects and solutions
Article • 12/05/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This introductory article explores what it means to create a solution and a project in
Visual Studio. A solution is a container to organize one or more related code projects,
like a class library project and a corresponding test project.
7 Note
Developing apps in Visual Studio doesn't require solutions and projects. You can
just open a folder that contains code and start coding, building, and debugging.
For example, a cloned GitHub repo might not contain Visual Studio projects and
solutions. For more information, see Develop code in Visual Studio without
projects or solutions.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page
to install it for free.
Create a solution
Start your exploration by creating an empty solution. After you get to know Visual
Studio, you probably won't create empty solutions often. When you create a new
project, Visual Studio automatically creates a solution for the project unless a solution is
already open.
1. Open Visual Studio, and on the start window, select Create a new project.
2. On the Create a new project page, type blank solution into the search box, select
the Blank Solution template, and then select Next.
Tip
If you have several workloads installed, the Blank Solution template might not
appear at the top of your list of search results. Try scrolling through Other
results based on your search to find the template.
3. On the Configure your new project page, name the solution QuickSolution, and
then select Create.
The QuickSolution solution appears in Solution Explorer on the right side of the
Visual Studio window. You'll use Solution Explorer often to browse the contents of
your projects.
Add a project
Now add your first project to the solution. Start with an empty project, and add the
items you need.
1. Right-click Solution 'QuickSolution' in Solution Explorer, and select Add > New
Project from the context menu.
2. On the Add a new project page, type empty into the search box at the top, and
select C# under All languages.
3. Select the C# Empty Project (.NET Framework) template, and then select Next.
7 Note
An easy way to install a new workload when you're creating a new project is
to select the Install more tools and features link under the text that says Not
finding what you're looking for?. In the Visual Studio Installer, select the .NET
desktop development workload, and then select Modify.
4. On the Configure your new project page, name the project QuickDate, and then
select Create.
The QuickDate project appears under the solution in Solution Explorer. The
project contains a References node and a single file named App.config.
The Add New Item dialog box opens. Select Show All Templates if dialog opens in
compact view.
2. Expand Visual C# Items, and then select Code. In the middle pane, select the Class
item template. Under Name, type Calendar, and then select Add.
Visual Studio adds a file named Calendar.cs to the project. The .cs on the end is the
file extension for C# code files. The Calendar.cs file appears in the Solution
Explorer visual project hierarchy, and the file opens in the editor.
3. Replace the contents of the Calendar.cs file with the following code:
C#
using System;
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 everything the code is doing yet. Run the app by
pressing Ctrl+F5, and see that the app prints today's date to the console, or
standard output, window. Then, close the console window.
To add a unit test project to your solution, start from a project template so you don't
have to add another code file to the project.
2. In the Add a new project dialog box, type unit test into the search box at the top,
and then select C# under All languages.
3. Select the C# Unit Test Project (.NET Framework) project template, and then select
Next.
4. On the Configure your new project page, name the project QuickTest, and then
select Create.
Visual Studio adds the QuickTest project to Solution Explorer, and the UnitTest1.cs
file opens in the editor.
1. In Solution Explorer, right-click the References node of the QuickTest project, and
select Add Reference from the context menu.
2. In the Reference Manager dialog box, select Projects. In the middle pane, select
the checkbox next to QuickDate, and then select OK.
C#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace QuickTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestGetCurrentDate()
{
Assert.AreEqual(DateTime.Now.Date,
QuickDate.Calendar.GetCurrentDate());
}
}
}
A red squiggle appears under some of the code. You can fix this error by making
the test project a friend assembly to the QuickDate project.
C#
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("QuickTest")]
Tip
You can also open Test Explorer by choosing Test > Test Explorer from the menu
bar.
Project properties
The line in the Calendar.cs file that contains the InternalsVisibleToAttribute attribute
references the assembly name or 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, use the project properties. The property pages contain various settings for the
project.
The property pages for the project open to the Application tab. The Assembly
name of the QuickTest project is indeed QuickTest.
If you want, you can change the name here. When you build the test project, the
name of the resulting binary file then changes from QuickTest.dll to
<NewName>.dll.
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.
See also
Work with projects and solutions
Develop code in Visual Studio without projects or solutions
Manage project and solution properties
Manage references in a project
Features of Visual Studio
Article • 08/24/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article describes features for experienced developers, or developers who are already
familiar with Visual Studio. For a basic introduction to Visual Studio, see the Visual
Studio IDE overview.
Modular installation
In Visual Studio's modular installer, you choose and install the workloads you want.
Workloads are groups of features that programming languages or platforms need to
work. This modular strategy helps keep the Visual Studio installation footprint smaller,
so it installs and updates faster.
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.
) Important
The Cloud Explorer window is retired in Visual Studio 2022. For more information,
see Manage the resources associated with your Azure accounts in Visual Studio
Cloud Explorer.
Use the Azure portal to access Azure resources as necessary. You can continue to
use the Azure node of Server Explorer in previous versions of Visual Studio.
You can use Azure services for your apps by adding Connected Services, such as:
Active Directory connected service, to use Azure Active Directory (Azure AD)
accounts 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 Services depend on your project type. Add a service by right-
clicking the project in Solution Explorer and choosing Add > Connected Service.
On the Connected Services screen, select the link or the plus sign to Add a service
dependency. On the Add dependency screen, select the service you want to add, and
follow the screens to connect to your Azure subscription and service.
For more information, see Move to the cloud With Visual Studio and Azure .
ASP.NET Core and .NET Core run on Windows, Mac, and Linux operating systems.
ASP.NET Core is a major update to MVC, WebAPI, and SignalR. ASP.NET Core is
designed from the ground up to provide a lean and composable .NET stack for building
modern cloud-based web apps and services.
Mobile apps for iOS, Android, and Windows in C# and F# by using Xamarin .
Native C++ apps for iOS, Android, and Windows devices. Share common code in
iOS, Android, and Windows libraries by using C++ for cross-platform development.
Connect to databases
Server Explorer helps you browse and manage server instances and assets locally,
remotely, and on Azure, Microsoft 365, Salesforce.com, and websites. To open Server
Explorer, choose View > Server Explorer. For more information on using Server
Explorer, see Add new connections.
SQL Server Object Explorer provides a view of your database objects, similar to SQL
Server Management Studio. With SQL Server Object Explorer, you can do light-duty
database administration and design work. Examples include editing table data,
comparing schemas, and executing queries by using contextual menus.
To open SQL Server Object Explorer, select its icon at the top of the Server Explorer
window, or select View > SQL Server Object Explorer from the Visual Studio top menu.
SQL Server Data Tools (SSDT) is a powerful development environment for SQL Server,
Azure SQL Database, and Azure SQL Data Warehouse. With SSDT, you can build, debug,
maintain, and refactor databases. You can work with a database project, or directly with
a connected database instance on- or off-premises. To get SSDT, use the Visual Studio
Installer to install the Data storage and processing workload.
For more information about debugging in Visual Studio, see First look at the debugger.
To improve app performance, check out the Visual Studio profiling feature.
Visual Studio offers testing options like unit testing, Live Unit Testing, IntelliTest, and
load and performance testing. Visual Studio also has advanced code analysis capabilities
to find design, security, and other flaws.
For full details, see the Git experience in Visual Studio page and the Visual Studio
version control documentation navigation page. And, for a step-by-step tutorial on how
to connect to a Git or Azure DevOps repository by using Visual Studio, see the Open a
project from a repo page.
Tip
We continue to build out the Git feature set and iterate on it based on your
feedback. For more info about a recent feature update along with a link to survey
where you can share your feedback on it, see the Multi-repo support in Visual
Studio blog post.
This feature is currently in public preview. This information relates to a feature that
may be substantially modified before it's released. Microsoft makes no warranties,
expressed or implied, with respect to the information provided here.
With Visual Studio 17.7 Preview 3 , you can pregenerate Visual Studio caches and
include them in your dev box image. As a result, Visual Studio will load your solution
and enable key IDE features faster on your dev box. You can also improve the Git
performance on large repositories by enabling Git commit-graph optimizations in dev
box images.
Next steps
If Visual Studio doesn't have the exact functionality you need, you can add it.
Personalize the IDE based on your workflow and style, add support for external
tools that aren't integrated with Visual Studio, and modify existing functionality to
increase your productivity. For the latest version of the Visual Studio Extensibility
Tools (VS SDK), see Visual Studio SDK.
You can use the .NET Compiler Platform Roslyn to write your own code analyzers
and code generators. Find everything you need at Roslyn .
Find existing extensions for Visual Studio created by Microsoft developers and
the Visual Studio development community.
To learn more about extending Visual Studio, see Extend Visual Studio IDE .
See also
Visual Studio IDE overview
What's new in Visual Studio 2017
What's new in Visual Studio 2019
What's new in Visual Studio 2022
Tutorial: Create a simple C# console app
in Visual Studio (part 1 of 2)
Article • 11/17/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, you use Visual Studio to create and run a C# console app, and explore
some features of the Visual Studio integrated development environment (IDE). This
tutorial is part 1 of a two-part tutorial series.
In part 2, you extend this app to add more projects, learn debugging tricks, and
reference third-party packages.
Prerequisites
You must have Visual Studio installed.
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, create a C# application project. The project type comes with all the template
files you need.
1. Open Visual Studio, and select Create a new project in the Start window.
2. In the Create a new project window, select All languages, and then choose C#
from the dropdown list. Choose Windows from the All platforms list, and choose
Console from the All project types list.
After you apply the language, platform, and project type filters, choose the
Console App template, and then select Next.
7 Note
If you don't see the Console App template, select Install more tools and
features.
In the Visual Studio Installer, select the .NET desktop development workload.
Select Modify in the Visual Studio Installer. You might be prompted to save
your work. Select Continue to install the workload.
Return to step 2 in this "Create a project" procedure.
3. In the Configure your new project window, type or enter Calculator in the Project
name box, and then select Next.
4. In the Additional information window, select .NET 8.0 for the Target Framework
field. Then, select Create.
Visual Studio opens your new project, which includes default "Hello World" code. To
view it in the editor, select the code file Program.cs in the Solution Explorer window,
which is typically on the right-hand side of Visual Studio.
The single code statement calls the WriteLine method to display the literal string "Hello,
World!" in the console window. If you press F5, you can run the default program in
Debug mode. After the application runs in the debugger, the console window stays
open. Press any key to close the console window.
7 Note
Starting with .NET 6, new projects using the console template generate different
code than previous versions. To learn more, see the New C# templates generate
top-level statements page.
1. In Solution Explorer, in the right pane, select Program.cs to display the file in the
code editor
2. In the code editor, replace the default "Hello World" code that says
Console.WriteLine("Hello World!"); .
Replace the line with the following code:
C#
int a = 42;
int b = 119;
int c = a + b;
Console.WriteLine(c);
Console.ReadKey();
If you enter the code, the Visual Studio IntelliSense feature offers you the option to
autocomplete the entry.
3. To build and run your app, press F5, or select the green arrow next to the name
Calculator in the top toolbar.
A console window opens that shows the sum of 42 + 119, which is 161.
5. Optionally, 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. When you run the app, the result changes
accordingly.
1. In the code editor, replace all the code in Program.cs with the following new code:
C#
3. In the console window, follow the prompts to add the numbers 42 and 119
together.
The current calculator app only accepts and returns whole numbers. For example, if you
run the app and divide the number 42 by the number 119, your result is zero, which isn't
exact.
1. From Program.cs in the Visual Studio editor, press Ctrl+H to open the Find and
Replace control.
2. Type int in the control, and type float in the Replace field.
3. Select the icons for Match case and Match whole word in the control, or press
Alt+C and Alt+W.
4. Select the Replace all icon or press Alt+A to run the search and replace.
5. Run your calculator app again, and divide the number 42 by the number 119.
6. Use the Find and Replace control to change each instance of the float variable to
double , and to change each instance of the Convert.ToInt32 method to
Convert.ToDouble .
7. Run your calculator app, and divide the number 42.5 by the number 119.75.
The app now accepts decimal values, and returns a longer decimal numeral as its
result.
In the Revise the code section, you reduce the number of decimal places in the
results.
Let's walk through a few common user input errors, locate them in the debugger if they
appear there, and fix them in the code.
Tip
For more information about the debugger and how it works, see First look at the
Visual Studio debugger.
7 Note
Sometimes the app doesn't freeze, and the debugger doesn't show a divide-by-
zero error. Instead, the app might return an unexpected nonnumeric result, such as
an infinity symbol. The following code fix still applies.
Let's change the code to handle this error. In Program.cs, replace the code for case "d":
with the following code:
C#
After you replace 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 asks for another number, and keeps
asking until you provide a nonzero number.
Fix the "format" error
If you enter an alphabetic character when the app expects a numeric character, the app
freezes. Visual Studio shows you what's wrong in the code editor.
To prevent this exception, you can refactor the code you've previously entered.
Rather than rely on the program class to handle all the code, you can divide your app
into two classes: Calculator and Program .
The Calculator class handles the bulk of the calculation work, and the Program class
handles the user interface and error-handling work.
C#
class Calculator
{
public static double DoOperation(double num1, double num2, string
op)
{
double result = double.NaN; // Default value is "not-a-number"
if an operation, such as division, could result in an error.
C#
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");
4. Follow the prompts and divide the number 42 by the number 119. Your results
should look similar to the following screenshot:
You can now run more calculations until you choose to close the console app.
There are also fewer decimal places in the results. And if you enter an incorrect
character, you get an appropriate error response.
Tip
Git is the most widely used modern version control system, so whether you're a
professional developer or you're learning how to code, Git can be very useful. If
you're new to Git, the https://git-scm.com/ website is a good place to start.
There, you can find cheat sheets, a popular online book, and Git Basics videos.
To associate your code with Git, start by creating a new Git repository where your code
is located:
1. In the status bar at the bottom-right corner of Visual Studio, select Add to Source
Control, and then select Git.
Tip
Whether your repository is public or private, it's best to have a remote backup
of your code stored securely on GitHub. Even if you aren't working with a
team, a remote repository makes your code available to you from any
computer.
After you create your repository, you see status details in the status bar.
The first icon with the arrows shows how many outgoing/incoming commits are in
your current branch. You can use this icon to pull any incoming commits or push
any outgoing commits. You can also choose to view these commits first. To do so,
select the icon, and then select View Outgoing/Incoming.
The second icon with the pencil shows the number of uncommitted changes to
your code. You can select this icon to view those changes in the Git Changes
window.
To learn more about how to use Git with your app, see the Visual Studio version control
documentation.
C#
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.
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");
Next steps
Continue with the second part of this tutorial:
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In part 2 of this tutorial series, you dive a little deeper into the Visual Studio build and
debug features you need for daily development. These features include managing
multiple projects, debugging, and referencing third-party packages. You run the C#
console app you created in Part 1 of this tutorial, and explore some features of the
Visual Studio integrated development environment (IDE). This tutorial is part 2 of a two-
part tutorial series.
Prerequisites
To work through this article, you can use either of these calculator apps:
In Visual Studio, you use the menu command File > Add > New Project to add a new
project. You can also right-click on the solution in Solution Explorer to add a project
from the context menu.
1. In Solution Explorer, right-click the solution node and choose Add > New Project.
2. In the Add a new project window, type class library in the Search box. Choose the
C# Class library project template, and then select Next.
3. On the Configure your new project screen, type the project name
CalculatorLibrary, and then select Next.
Visual Studio creates the new project and adds it to the solution.
5. Rename the Class1.cs file to CalculatorLibrary.cs. To rename the file, you can right-
click the name in Solution Explorer and choose Rename, select the name and
press F2, or select the name and select again to type.
A message might ask whether you want to rename all references to Class1 in the
file. It doesn't matter how you answer, because you'll replace the code in a future
step.
6. Now add a project reference, so the first project can use APIs that the new class
library exposes. Right-click the Dependencies node in the Calculator project and
choose Add Project Reference.
The Reference Manager dialog box appears. In this dialog box, you can add
references to other projects, assemblies, and COM DLLs that your projects need.
7. In the Reference Manager dialog box, select the checkbox for the
CalculatorLibrary project, and then select OK.
The project reference appears under a Projects node in Solution Explorer.
8. In Program.cs, select the Calculator class and all its code, and press Ctrl+X to cut
it. Then, in CalculatorLibrary.cs, paste the code into the CalculatorLibrary
namespace.
Also add public before the Calculator class to expose it outside the library.
C#
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" if an operation, such as division, could result in an error.
9. Program.cs also has a reference, but an error says the Calculator.DoOperation call
doesn't resolve. The error is because CalculatorLibrary is in a different
namespace. For a fully qualified reference, you could add the CalculatorLibrary
namespace to the Calculator.DoOperation call:
C#
result = CalculatorLibrary.Calculator.DoOperation(cleanNum1, cleanNum2,
op);
Or, you could try adding a using directive to the beginning of the file:
C#
using CalculatorLibrary;
Adding the using directive should let you remove the CalculatorLibrary
namespace from the call site, but now there's an ambiguity. Is Calculator the class
in CalculatorLibrary , or is Calculator the namespace?
C#
namespace CalculatorProgram
C#
using System.Diagnostics;
2. This usage of the Trace class must hold onto a reference for the class, which it
associates with a filestream. That requirement means the calculator works better as
an object, so add a constructor at the beginning of the Calculator class in
CalculatorLibrary.cs.
Also remove the static keyword to change the static DoOperation method into a
member method.
C#
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. Add log output to each calculation. DoOperation should now look like the
following code:
C#
4. Back in Program.cs, a red squiggly underline now flags the static call. To fix the
error, create a calculator variable by adding the following code line just before
the while (!endApp) loop:
C#
Also modify the DoOperation call site to reference the object named calculator in
lowercase. The code is now a member invocation, rather than a call to a static
method.
C#
5. Run the app again. When you're done, right-click the Calculator project node and
choose Open Folder in File Explorer.
6. In File Explorer, navigate to the output folder under bin/Debug/, and open the
calculator.log file. The output should look something like this:
Output
C#
using System.Diagnostics;
namespace CalculatorLibrary
{
public class Calculator
{
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()));
}
C#
using CalculatorLibrary;
namespace CalculatorProgram
{
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");
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");
2. Search for and select the Newtonsoft.Json package, and select Install.
If you're prompted whether to accept changes, select OK.
Visual Studio downloads the package and adds it to the project. A new entry
appears in a Packages node in Solution Explorer.
C#
using Newtonsoft.Json;
3. Create the JsonWriter member object, and replace the Calculator constructor
with the following code:
C#
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();
}
C#
return result;
}
5. Add a method to finish the JSON syntax once the user is done entering operation
data.
C#
C#
7. Build and run the app, and after you're done entering a few operations, close the
app by entering the n command.
8. Open the calculatorlog.json file in File Explorer. You should see something like the
following content:
JSON
{
"Operations": [
{
"Operand1": 2.0,
"Operand2": 3.0,
"Operation": "Add",
"Result": 5.0
},
{
"Operand1": 3.0,
"Operand2": 4.0,
"Operation": "Multiply",
"Result": 12.0
}
]
}
1. In Program.cs, click in the gutter to the left of the following code line. You can also
click in the line and select F9, or right-click the line and select Breakpoint > Insert
Breakpoint.
C#
The red dot that appears indicates a breakpoint. You can use breakpoints to pause
your app and inspect code. You can set a breakpoint on any executable line of
code.
2. Build and run the app. Enter the following values for the calculation:
The app suspends where you created the breakpoint, which is indicated by the
yellow pointer on the left and the highlighted code. The highlighted code hasn't
yet executed.
Now, with the app suspended, you can inspect your application state.
Debug: View variables
1. In the highlighted code, hover over variables such as cleanNum1 and op . The
current values for these variables, 8 and d respectively, appear in DataTips.
When debugging, checking to see whether variables hold the values you expect is
often critical to fixing issues.
2. In the lower pane, look at the Locals window. If it's closed, select Debug >
Windows > Locals to open it.
The Locals window shows each variable that's currently in scope, along with its
value and type.
The Autos window is similar to the Locals window, but shows the variables
immediately preceding and following the current line of code where your app is
paused.
7 Note
If you don't see the Autos window, select Debug > Windows > Autos to open
it.
Next, execute code in the debugger one statement at a time, which is called stepping.
Using the Step Into command, the app executes the current statement and
advances to the next executable statement, usually the next line of code. The
yellow pointer on the left always indicates the current statement.
You just stepped into the DoOperation method in the Calculator class.
2. To get a hierarchical look at your program flow, look at the Call Stack window. If
it's closed, select Debug > Windows > Call Stack to open it.
The Call Stack window shows the order in which methods and functions are
getting called. This window also provides access to many debugger features, such
as Go to Source Code, from its shortcut menu.
3. Press F10, or select Debug > Step Over, several times until the app pauses on the
switch statement.
C#
switch (op)
{
The Step Over command is similar to the Step Into command, except that if the
current statement calls a function, the debugger runs the code in the function, and
doesn't suspend execution until the function returns. Step Over is faster than Step
Into if you're not interested in a particular function.
4. Press F10 one more time, so that the app pauses on the following line of code.
C#
if (num2 != 0)
{
This code checks for a divide-by-zero case. If the app continues, it throws a general
exception (an error), but you might want to try something else, like viewing the
actual returned value in the console. One option is to use a debugger feature
called edit-and-continue to make changes to the code and then continue
debugging. However, there's a different trick to temporarily modify the execution
flow.
C#
Dragging the pointer here causes the app to completely skip the if statement, so
you can see what happens when you divide by zero.
3. If you hover over the result variable, it shows a value of Infinity. In C#, Infinity is
the result when you divide by zero.
The infinity symbol appears in the console as the result of the math operation.
Code complete
Here's the complete code for the CalculatorLibrary.cs file, after you complete all the
steps:
C#
using Newtonsoft.Json;
namespace CalculatorLibrary
{
public class Calculator
{
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;
}
C#
using CalculatorLibrary;
namespace CalculatorProgram
{
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");
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");
Next steps
Congratulations on completing this tutorial! To learn more, continue with the following
content:
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial for C# development with ASP.NET Core, you create a C# ASP.NET Core
web app in Visual Studio.
Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads
page for a free version.
For more information about upgrading to the latest Visual Studio release, see
Visual Studio updates.
To customize your Visual Studio experience, see personalize the Visual Studio IDE
and Editor.
Create a project
First, you create an ASP.NET Core project. The project type comes with all the template
files you need to build a fully functional website.
After you apply the language, platform, and project type filters, select the ASP.NET
Core Web App template, and then select Next.
7 Note
If you don't see the ASP.NET Core Web App template, you can install it from
the Create a new project window.
In the Not finding what you're looking for? message at the bottom of the list
of templates, select the Install more tools and features link.
In the Visual Studio Installer, select the ASP.NET and web development
workload.
Select Modify in the Visual Studio Installer. You might be prompted to save
your work. Select Continue to install the workload.
3. In the Configure your new project window, enter MyCoreApp in the Project name
field. Then, select Next.
4. In the Additional information window, verify that .NET 8.0 appears in the Target
Framework field.
From this window, you can enable Docker support and add authentication support.
The drop-down menu for Authentication Type has the following four options:
None: No authentication.
Individual accounts: These authentications are stored in a local or Azure-
based database.
Microsoft identity platform: This option uses Microsoft Entra ID or Microsoft
365 for authentication.
Windows: Suitable for intranet applications.
Leave the Enable Docker box unchecked, and select None for Authentication Type.
5. Select Create.
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. In the toolbar, select the IIS Express button to build and run the app in debug
mode. Alternatively, press F5, or go to Debug > Start Debugging from the menu
bar.
7 Note
If you get an error message that says Unable to connect to web server 'IIS
Express', close Visual Studio and then relaunch the program as an
administrator. You can do this task by right-clicking the Visual Studio icon
from the Start Menu, and then selecting the Run as administrator option
from the context menu.
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, select Yes, and then
select 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. Select Privacy from the menu bar. The Privacy page in the browser renders the text
that's set in the Privacy.cshtml file.
4. Return to Visual Studio, and then press Shift+F5 to stop debugging. This action
closes the project in the browser window.
5. In Visual Studio, open Privacy.cshtml for editing. Next, delete the sentence, Use
this page to detail your site's privacy policy and replace it with This page is under
construction as of @ViewData["TimeStamp"].
6. Now, let's make a code change. Select Privacy.cshtml.cs. Then, clean up the using
directives at the top of the file by selecting the following shortcut:
Mouseover or select a greyed out using directive. A Quick Actions light bulb
appears below the caret or in the left margin. Select the light bulb, and then select
the expand arrow next to Remove unnecessary usings.
Now select Preview changes to see what changes.
Select Apply. Visual Studio deletes the unnecessary using directives from the file.
7. Next, create a string for the current date that's formatted for your culture or region
by using the DateTime.ToString method.
The first argument for the method specifies how the date should be
displayed. This example uses the format specifier ( d ) which indicates the
short date format.
The second argument is the CultureInfo object that specifies the culture or
region for the date. The second argument determines, among other things,
the language of any words in the date, and the type of separators used.
C#
8. Notice that the following using directive automatically gets added to the top of
the file:
C#
using System.Globalization;
10. At the top of the web site, select Privacy to view your changes.
In the code editor, you see HTML code for the text that appears on the Home
page.
4. In the web browser, you see your new changes on the Home page.
5. Close the web browser, press Shift+F5 to stop debugging, and save your project.
You can now close Visual Studio.
Next steps
Congratulations on completing this tutorial! We hope you enjoyed learning 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 tutorial:
See also
Publish your web app to Azure App Service by using Visual Studio
Tutorial: Create your first Windows App
SDK application in Visual Studio with
XAML and C#
Article • 01/12/2024
7 Note
WinUI 3 is the native UI platform component that ships with the Windows App
SDK (completely decoupled from Windows SDKs). For more information, see
WinUI 3.
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 WinUI 3 project. The project type comes with all the template files you
need, before you've even added anything!
1. Open Visual Studio, and on the start window, choose Create a new project.
2. On the Create a new project screen, enter WinUI in the search box, choose the C#
template for Blank App, Packaged (WinUI 3 in Desktop), and then choose Next.
7 Note
If you don't see the Blank App, Packaged (WinUI 3 in Desktop) project
template, click the Install more tools and features link.
The Visual Studio Installer launches. Choose the .NET Desktop Development
workload, then in the Installation details pane of the installation dialog box,
select Windows App SDK C# Templates (at the bottom of the list). Now select
Modify.
3. Give the project a name, HelloWorld, and choose Create.
7 Note
If this is the first time you have used Visual Studio to create a Windows App
SDK 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.
The XAML Editor is where you can add or change markup. Unlike UWP projects,
WinUI 3 doesn't have a Design view.
2. Review the Button control nested within the StackPanel at the root of the Window.
2. Notice that the button has a Click event handler named myButton_Click specified,
too. We'll get to that in the next step.
Modify the event handler
An "event handler" sounds complicated, but it's just another name for code that is called
when an event happens. In this case, it adds an action triggered by the "Hello World!"
button.
2. Edit the event handler code in the C# editor window that opens.
Here is where things get interesting. The default event handler looks like this:
C#
1. Use the Play button (it has the text HelloWorld (Package)) to start the application
on the local machine.
(Alternatively, you can choose Debug > Start 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 image:
3. Select the Hello World button.
Your Windows 10 or later device will display a message that says "Welcome to your
first Windows App SDK app" with the title "Hello from HelloWorld." Click Ok to
dismiss the message.
4. To close the app, select the Stop Debugging button in the toolbar. (Alternatively,
choose Debug > Stop debugging from the menu bar, or press Shift+F5.)
Next steps
Congratulations on completing this tutorial! We hope you learned some basics about
Windows App SDK, WinUI 3, and the Visual Studio IDE. To learn more, continue with the
following tutorial:
See also
Writing apps for Windows: Selecting a development technology
Windows App SDK overview
Windows App SDK / WinUI 3 samples
Tutorial: Create your first Universal
Windows Platform application in Visual
Studio with XAML and C#
Article • 05/31/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
7 Note
If you're happy with your current functionality in the Universal Windows Platform
(UWP), then there's no need to migrate your project type to Windows App SDK.
WinUI 2.x, and the Windows SDK, support UWP project types. If you would like to
get started with WinUI 3 and Windows App SDK, then you can follow the steps in
the Windows App SDK tutorial.
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, 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.
7 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 select Modify.
3. Give the project a name, HelloWorld, and choose Create.
4. Accept the default Target version and Minimum version settings in the New
Universal Windows Platform Project dialog box.
7 Note
If this is the first time you have used Visual Studio to create a UWP app, the
Enable Developer Mode for Windows dialog will appear. Select settings for
developers to open Settings. Turn on 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.
Here is where things get interesting. The default event handler looks like this:
C#
1. Use the Play button (it has the text Local Machine) to start the application on the
local machine.
(Alternatively, you can choose Debug > Start 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 image:
3. Select the Hello World button.
4. To close the app, select the Stop Debugging button in the toolbar. (Alternatively,
choose Debug > Stop debugging from the menu bar, or press Shift+F5.)
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:
See also
UWP overview
Get UWP app samples
Tutorial: Create a simple WPF
application with C#
Article • 11/17/2023
By completing this tutorial, you become familiar with many of the tools, dialog boxes,
and designers that you can use when you develop applications with Visual Studio. You
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.
Make sure the .NET desktop development workload is installed. You can verify this
configuration in the Visual Studio Installer.
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.
What is WPF?
WPF, or Windows Presentation Foundation, is a UI (user interface) framework that
creates desktop client applications. The WPF development platform supports a broad
set of application development features, including an application model, resources,
controls, graphics, layout, data binding, documents, and security.
WPF is part of .NET, so if you have previously built applications with .NET using ASP.NET
or Windows Forms, the programming experience should be familiar. WPF uses the
Extensible Application Markup Language XAML to provide a declarative model for
application programming. For more information, see WPF .NET overview.
3. On the Create a new project screen, search for "WPF," choose WPF Application,
and then choose Next.
4. At the next screen, give the project a name, HelloWPFApp, and choose Next.
5. In the Additional information window, verify that .NET 8.0 is selected for your
target framework. Then, 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.
7 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 Properties 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.
We add three types of controls to this application: a TextBlock control, two RadioButton
controls, and a Button control.
2. In the Toolbox, expand the Common WPF Controls node to see the TextBlock
control.
3. Add a TextBlock control to the design surface by choosing the TextBlock item and
dragging it to the window on the design surface. Center the control near the top of
the window. You can use the guidelines to center the control.
The XAML markup should look something like the following example:
XAML
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="387,60,0,0"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
</Grid>
Customize the text in the text block
1. In the XAML view, locate the markup for TextBlock and change the Text attribute
from TextBox to Select a message option and then choose the Display button.
The XAML markup should look something like the following example:
XAML
<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.
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. You can use the guidelines to align the controls.
4. In the Properties window for the right RadioButton control, change the Name
property to GoodbyeButton , and then save your changes.
Next, you add display text for each RadioButton control. The following procedure
updates the Content property for a RadioButton control.
XAML
<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>
The XAML markup should now look similar to the following example:
XAML
<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>
2. In the XAML view, change the value of Content for the Button control from
Content="Button" to Content="Display" , and then save the changes.
The XAML markup should now look similar to the following example:
XAML
<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>
C#
The XAML markup should now look similar to the following example:
XAML
<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"
Click="Button_Click"/>
</Grid>
C#
if (HelloButton.IsChecked == true)
{
MessageBox.Show("Hello.");
}
else if (GoodbyeButton.IsChecked == true)
{
MessageBox.Show("Goodbye.");
}
3. Save the application.
A Break Mode window appears, and the Output window indicates that an
IOException has occurred: Cannot locate resource mainwindow.xaml.
As an optional step, it avoids confusion to change the title of your application window
to match this new name.
1. In Solution Explorer, open the Greetings.xaml file that you just renamed.
Start the debugger again (press F5). You should now see the Greetings window of your
application.
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.
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 application resumes execution, and a message box with the word "Hello"
appears.
9. Choose the F5 key to continue debugging. When the message box appears,
choose the OK button on the message box to close it.
11. On the menu bar, choose Debug > Disable All Breakpoints.
2. Change the build configuration for HelloWPFApp from Debug to Release by using
the dropdown control on the toolbar (it says "Debug" currently).
Congratulations on completing this tutorial! You can find the .exe you built under your
solution and project directory (...\HelloWPFApp\HelloWPFApp\bin\Release).
Next steps
Congratulations on completing this tutorial! To learn even more, continue with the
following tutorials.
See also
Productivity tips
Create a Windows Forms app in Visual
Studio with C#
Article • 01/25/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, 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 2022 downloads
page to install it for free.
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.
3. On the Create a new project window, select the Windows Forms App (.NET
Framework) template for C#.
(If you prefer, you can refine your search to quickly get to the template you want.
For example, enter or type Windows Forms App in the search box. Next, select C#
from the Language list, and then select Windows from the Platform list.)
7 Note
If you do not see the Windows Forms App (.NET Framework) template, you
can install it from the Create a new project window. In the Not finding what
you're looking for? message, select the Install more tools and features link.
Next, in the Visual Studio Installer, select the .NET desktop development
workload.
After that, select the Modify button in the Visual Studio Installer. You might
be prompted to save your work; if so, do so. Next, select 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, select Create.
2. Expand Common Controls and select the Pin icon to dock the Toolbox window.
3. Select the Button control and then drag it onto the form.
4. In the Properties window, locate Text, change the name from button1 to Click
this , and then press Enter.
(If you don't see the Properties window, you can open it from the menu bar. To do
so, select View > Properties Window. Or, press F4.)
5. In the Design section of the Properties window, change the name from button1 to
btnClickThis , and then press Enter.
7 Note
1. Select the Label control from the Toolbox window, and then drag it onto the form
and drop it beneath the Click this button.
2. In the Form1.cs window, after the private void line, type or enter
lblHelloWorld.Text = "Hello World!"; as shown in the following screenshot:
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. Select the Click this button in the Form1 dialog box. Notice that the label1 text
changes to Hello World!.
3. Close the Form1 dialog box to stop running the app.
Next steps
Congratulations on completing this tutorial. To learn more, continue with the following
tutorial:
See also
More C# tutorials
Visual Basic tutorials
C++ tutorials
Tutorial: Create a picture viewer
Windows Forms app in Visual Studio
Article • 02/28/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a
picture and displays it. The Visual Studio Integrated Design Environment (IDE) provides
the tools you need to create the app. To learn more, see Welcome to the Visual Studio
IDE.
Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads
page for a free version.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual
Basic, and then select Next.
7 Note
If you don't see the Windows Forms App (.NET Framework) template, you
can install it from the Create a new project window. In the Not finding what
you're looking for? message, select the Install more tools and features link.
Select Modify in the Visual Studio Installer. You might be prompted to save
your work. Next, select Continue to install the workload.
5. In the Configure your new project window, name your project PictureViewer, then
select Create.
Visual Studio creates a solution for your app. A solution is a container for all of the
projects and files needed by your app.
At this point, Visual Studio displays an empty form in the Windows Form Designer.
1. In your project, select the Windows Forms Designer. The tab reads Form1.cs
[Design] for C# or Form1.vb [Design] for Visual Basic.
3. The Properties window now displays properties for the form. The Properties
window is usually in the lower right of Visual Studio. This section controls various
properties, such as foreground and background color, title text that appears at the
top of the form, and the size of the form.
4. Find the Text property in the Properties window. Depending on how the list is
sorted, you might need to scroll down. Enter the value Picture Viewer, and then
choose Enter.
Your form now has the text Picture Viewer in its title bar.
7 Note
5. Select the form, again. Select the form's lower-right drag handle. The handle is a
small white square in the lower-right corner of the form.
Drag the handle to resize the form so the form is wider and a bit taller. If you look
at the Properties window, the Size property has changed. You can also change the
size of the form by changing the Size property.
6. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it,
select View > Toolbox from the menu bar or Ctrl+Alt+X.
7. Select the small triangle symbol next to Containers to open the group.
8. Double-click TableLayoutPanel in the Toolbox. You can also drag a control from
the toolbox onto the form. The TableLayoutPanel control appears in your form.
7 Note
After you add your TableLayoutPanel, if a window appears inside your form
with the title TableLayoutPanel Tasks, click anywhere inside the form to close
it.
9. Select the TableLayoutPanel. You can verify what control is selected by looking at
the Properties window.
10. With the TableLayoutPanel selected, find the Dock property, which has the value
None. Select the dropdown arrow and then select Fill, which is the large button in
the middle of the dropdown menu.
The TableLayoutPanel now fills the entire form. If you resize the form again, the
TableLayoutPanel stays docked, and resizes itself to fit.
11. In the form, select the TableLayoutPanel. In the upper-right corner, there's a small
black triangle button.
13. Select Column1 and set its size to 15 percent. Be sure the Percent button is
selected.
15. From Show at the top of the Column and Row Styles dialog box, select Rows. Set
Row1 to 90 percent and Row2 to 10 percent. Select OK to save your changes.
Your TableLayoutPanel now has a large top row, a small bottom row, a small left
column, and a large right column.
Your layout is complete.
7 Note
Before you run your application, save your app by choosing the Save All toolbar
button. Alternatively, to save your app, choose File > Save All from the menu bar,
or press Ctrl+Shift+S. It's a best practice to save early and often.
Visual Studio runs your app. A window with the title Picture Viewer appears.
Look at the Visual Studio IDE toolbar. More buttons appear on the toolbar when
you run an application. These buttons let you do things like stop and start your
app, and help you track down any errors.
When you run your app from inside the Visual Studio IDE, it's called debugging.
You run your application to find and fix bugs. You follow the same procedure to
run and debug other programs. To learn more about debugging, see First look at
the debugger.
Next steps
Advance to the next tutorial to learn how to add controls to your Picture Viewer
program.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a
picture and displays it. The Visual Studio Integrated Design Environment (IDE) provides
the tools you need to create the app. To learn more, see Welcome to the Visual Studio
IDE.
This program has a picture box, a checkbox, and several buttons, which you use to
control the application. This tutorial shows you how to add these controls.
Prerequisites
This tutorial builds on the previous tutorial, Create a picture viewer application. If you
haven't done that tutorial, go through that one first.
1. Open Visual Studio. Your Picture Viewer project appears under Open recent.
2. In the Windows Forms Designer, select the TableLayoutPanel you added in the
previous tutorial. Check that tableLayoutPanel1 appears in the Properties window.
3. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it,
select View > Toolbox from the menu bar or Ctrl+Alt+X. In the toolbox, expand
Common Controls.
5. Choose the new PictureBox control to select it, and then select the black triangle
on the new PictureBox control to display its task list.
6. Select Dock in Parent Container, which sets the PictureBox Dock property to Fill.
You can see that value in the Properties window.
7. In the Properties window for the PictureBox, set the ColumnSpan property to 2.
The PictureBox now fills both columns.
1. Select the TableLayoutPanel on the form. Open the Toolbox, select Containers.
Double-click FlowLayoutPanel to add a new control to the last cell of the
TableLayoutPanel.
2. Set the FlowLayoutPanel's Dock property to Fill. You can set this property by
selecting the black triangle, then selecting Dock in parent container.
3. Select the new FlowLayoutPanel, and then open the Toolbox and select Common
Controls. Double-click the Button item to add a button control called button1.
4. Double-click Button again to add another button. The IDE calls the next one
button2.
5. Add two more buttons this way. Another option is to select button2, and then
select Edit > Copy or press Ctrl+C. Next, choose Edit > Paste from the menu bar
or press Ctrl+V. To paste a copy of your button. Now paste it again. Notice that the
IDE adds button3 and button4 to the FlowLayoutPanel.
6. Select the first button and set its Text property to Show a picture.
7. Set the Text properties of the next three buttons to Clear the picture, Set the
background color, and Close.
8. To size the buttons and arrange them, select the FlowLayoutPanel. Set the
FlowDirection property to RightToLeft.
The buttons should align themselves to the right side of the cell, and reverse their
order so that the Show a picture button is on the right. You can drag the buttons
around the FlowLayoutPanel to arrange them in any order.
9. Choose the Close button to select it. Then, to choose the rest of the buttons at the
same time, press and hold the Ctrl key and choose them, too.
10. In the Properties window, set the AutoSize property to True. The buttons resize to
fit their text.
You can run your program to see how the controls look. Select the F5 key, select Debug
> Start Debugging, or select the Start button. The buttons that you added don't do
anything, yet.
1. On the form, choose the Close button. If you still have all the buttons selected,
choose Esc to cancel the selection.
2. In the Properties window, look for (Name). Change the name to closeButton.
You can change the name of any control, such as the TableLayoutPanel or checkbox.
Unlike a control, adding a component to your form doesn't add a visible item. Instead, it
provides certain behaviors that you can trigger with code. For instance, it's a component
that opens an Open File dialog box.
In this section, you add an OpenFileDialog component and a ColorDialog component to
your form.
1. Select the Windows Forms Designer (Form1.cs [Design]). Then open the Toolbox
and select the Dialogs group.
Console
The Filter property settings specify the types that the Select a picture dialog box
displays.
Next steps
Advance to the next tutorial to learn how to add code to your application.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a
picture and displays it. The Visual Studio Integrated Design Environment (IDE) provides
the tools you need to create the app. To learn more, see Welcome to the Visual Studio
IDE.
Controls use C# or Visual Basic code to take the actions associated with them.
Prerequisites
This tutorial builds on the previous tutorials, Create a picture viewer application and Add
UI controls to the picture viewer. If you haven't done those tutorials, go through them
first.
1. Open Visual Studio. Your Picture Viewer project appears under Open recent.
2. In the Windows Forms Designer, double-click the Show a picture button. You can
instead select the Show a picture button on the form, and then press Enter.
The Visual Studio IDE opens a tab in the main window. For C#, the tab is named
Form1.cs. If you're using Visual Basic, the tab is named Form1.vb.
C#
C#
) Important
Use the programming language control at the top right of this page to view
either the C# code snippet or the Visual Basic code snippet.
4. Choose the Windows Forms Designer tab again, and then double-click the Clear
the picture button to open its code. Repeat for the remaining two buttons. Each
time, the Visual Studio IDE adds a new method to the form's code file.
The following snippet shows the new code that you see in the code editor.
C#
C#
Methods, including event handlers, can have any name that you want. When you add an
event handler with the IDE, it creates a name based on the control's name and the event
being handled.
For example, the Click event for a button named showButton is called
showButton_Click() or ShowButton_Click() . If you want to change a code variable name,
right-click the variable in the code and then choose Refactor > Rename. All instances of
that variable in the code are renamed. For more information, see Rename refactoring.
The Visual Studio IDE offers a powerful tool called IntelliSense. As you type, IntelliSense
suggests possible code.
1. In Windows Forms Designer, double-click the Show a picture button. The IDE
moves your cursor inside the showButton_Click() or ShowButton_Click() method.
2. Type an i on the empty line between the two braces { } or between Private
Sub... and End Sub . An IntelliSense window opens.
3. The IntelliSense window should highlight the word if . Select the Tab key to insert
if .
4. Select true and then type op to overwrite it for C# or Op for Visual Basic.
7. Add parentheses () immediately after the "g" in ShowDialog . Your code should be
openFileDialog1.ShowDialog() .
8. For C#, add a space, and then add two equal signs ( == ). For Visual Basic, add a
space, and then use a single equal sign ( = ).
10. Type a dot to open the DialogResult value in the IntelliSense window. Enter the
letter O and choose the Tab key to insert OK.
7 Note
The first line of code should be complete. For C#, it should be similar to the
following.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
C#
C#
pictureBox1.Load(openFileDialog1.FileName);
You can copy and paste or use IntelliSense to add it. Your final showButton_Click()
method should look similar to the following code.
C#
C#
private void showButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}
C#
C#
It's the best practice to always comment your code. Code comments make it easier to
understand and maintain your code in the future.
In this section, add the code for the other event handlers.
1. In Windows Forms Designer, double-click the Clear the picture button. Add the
code in the braces.
C#
C#
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the picture.
pictureBox1.Image = null;
}
2. Double-click the Set the background color button and add the code in braces.
C#
C#
C#
C#
C#
C#
A window with the title Picture Viewer appears. Test all the controls.
1. Select the Set the background color button. The Color dialog box opens.
5. Select the Clear the picture button to make sure the display clears.
Next steps
Congratulations! You've completed this series of tutorials. You've done these
programming and design tasks in the Visual Studio IDE:
Continue learning with another tutorial series on how to create a timed math quiz.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random
math problems that a quiz taker tries to answer within a specified time.
The Visual Studio integrated development environment (IDE) provides the tools that you
need to create the app. To learn more about this IDE, see Welcome to the Visual Studio
IDE.
Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads
page for a free version.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual
Basic, and then select Next.
7 Note
If you don't see the Windows Forms App (.NET Framework) template, you
can install it from the Create a new project window. In the Not finding what
you're looking for? message, select Install more tools and features.
Select Modify in Visual Studio Installer. You might be prompted to save your
work. Next, select Continue to install the workload.
5. In the Configure your new project window, name your project MathQuiz, and
then select Create.
Visual Studio creates a solution for your app. A solution is a container for all the projects
and files that your app needs.
1. In your project, select Windows Forms Designer. The designer tab is labeled
Form1.cs [Design] for C# or Form1.vb [Design] for Visual Basic.
3. The Properties window now displays properties for the form. This window is
usually in the lower right corner of Visual Studio. If you don't see Properties, select
View > Properties Window.
4. Find the Text property in the Properties window. Depending on how the list is
sorted, you might need to scroll down. Enter the value Math Quiz for the Text
value, and then select Enter.
Your form now has the text "Math Quiz" in its title bar.
7 Note
5. Change the size of the form to 500 pixels wide by 400 pixels tall.
You can resize the form by dragging its edges or drag handle until the correct size
appears as the Size value in the Properties window. The drag handle is a small
white square in the lower-right corner of the form. You can also resize the form by
changing the values of the Size property.
6. Change the value of the FormBorderStyle property to Fixed3D, and set the
MaximizeBox property to False.
1. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see
the toolbox, select View > Toolbox from the menu bar or Ctrl+Alt+X.
2. Select the Label control in the Toolbox, and then drag it onto the form.
3. In the Properties box, set the following properties for the label:
4. Move the label to the upper-right corner of the form. When blue spacer lines
appear, use them to position the control on the form.
5. Add another Label control from the Toolbox, and then set its font size to 15.75.
6. Set this label's Text property to Time Left.
7. Move the label so that it lines up to the left of the timeLabel label.
2. In the Properties box, set the following properties for the label:
3. In the form, select the plusLeftLabel label that you created. Copy the label by
selecting either Edit > Copy or Ctrl+C.
4. Paste the label into the form three times by selecting either Edit > Paste or Ctrl+V
three times.
5. Arrange the three new labels so that they are in a row to the right of the
plusLeftLabel label.
9. Add a NumericUpDown control from the Toolbox to the form. You'll learn more
about this kind of control later.
10. In the Properties box, set the following properties for the NumericUpDown
control:
11. Line up the NumericUpDown control with the Label controls for the addition
problem.
1. Copy the four Label controls and the NumericUpDown control that you created for
the addition problem. Paste them into the form.
3. In the Properties box, set the following properties for the new controls:
4. Copy the addition controls, and paste them two more times into the form.
4. In the Properties box, set the TabIndex property of each NumericUpDown control:
Select Ctrl+Shift+S.
On the menu bar, select File > Save All.
On the toolbar, select the Save All button.
2. Use one of the following methods to run your app:
Select F5.
On the menu bar, select Debug > Start Debugging.
On the toolbar, select the Start button.
3. Select the Tab key a few times to see how the focus moves from one control to the
next.
Next steps
Advance to the next tutorial to add random math problems and an event handler to
your math quiz.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random
math problems that a quiz taker tries to answer within a specified time.
Controls use C# or Visual Basic code. In this second tutorial, you make the quiz
challenging by adding code for math problems that are based on random numbers. You
also create a method that's named StartTheQuiz() to fill in the problems.
Prerequisites
This tutorial builds on a previous tutorial, Create a math quiz WinForms app. If you
haven't completed that tutorial, go through it first.
3. On the menu bar, select View > Code. Form1.cs or Form1.vb appears, depending
on the programming language that you're using, so that you can view the code
behind the form.
4. Create a Random object by adding a new statement near the top of the code.
C#
C#
public partial class Form1 : Form
{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
You can use new statements like this one to create buttons, labels, panels,
OpenFileDialogs, ColorDialogs, SoundPlayers, Randoms, and even forms. These items
are called objects.
When you run your program, the form is started. The code behind it creates a Random
object and names it randomizer.
Your quiz needs variables to store the random numbers that it creates for each problem.
Before using variables, you declare them, which means listing their names and data
types.
1. Add two integer variables to the form, and name them addend1 and addend2.
7 Note
You use similar syntax to add an integer variable as you did to add the Random
object, as the following code shows.
C#
C#
1. Add a method that's named StartTheQuiz() . This method uses the Random
object's Next() method to generate random numbers for the labels.
StartTheQuiz() will eventually fill in all the problems and then start the timer, so
add this information to the summary comment. The function should look like the
following code.
C#
C#
/// <summary>
/// Start the quiz by filling in all of the problems
/// and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);
50. This code calls randomizer.Next(51) so that the two random numbers add up to an
answer that's between 0 and 100.
C#
C#
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();
These statements set the Text properties of plusLeftLabel and plusRightLabel so that
they display the two random numbers. Label controls display values in text format, and
in programming, strings hold text. Each integer's ToString() method converts the
integer into text that a label can display.
1. Add integer variables for the remaining math problems to your form, after the
addition problem variables. The code should look like the following sample.
C#
C#
1. Modify the StartTheQuiz() method by adding the following code, starting with the
"Fill in the subtraction problem" comment.
C#
C#
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);
This code uses the Next() method of the Random class a little differently from how the
addition problem does. When you give the Next() method two values, it picks a
random number that's greater than or equal to the first value and less than the second
one.
By using the Next() method with two arguments, you can ensure the subtraction
problem has a positive answer, the multiplication answer is at most 100, and the division
answer isn't a fraction.
1. In Windows Forms Designer, either double-click the Start the quiz button, or
select it and then select Enter. The form's code appears, and a new method is
visible.
These actions add a Click event handler to the start button. When a quiz taker
selects this button, the app runs the code that you'll add to this new method.
2. Add the following two statements so that the event handler starts the quiz.
C#
C#
private void startButton_Click(object sender, EventArgs e)
{
StartTheQuiz();
startButton.Enabled = false;
}
The first statement calls the new StartTheQuiz() method. The second statement sets the
Enabled property of the startButton control to false so that the quiz taker can't select
the button during a quiz.
2. Run your app, and then select Start the quiz. Random math problems appear, as
the following screenshot shows.
Next steps
Advance to the next tutorial to add a timer to your math quiz and check user answers.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random
math problems that a quiz taker tries to answer within a specified time.
The quiz uses a Timer control. The code behind this control tracks the elapsed time and
checks the quiz taker's answers.
Prerequisites
This tutorial builds on previous tutorials, starting with Create a math quiz WinForms app.
If you haven't completed those tutorials, go through them first.
1. Add an integer variable that's named timeLeft in the same way that you declared
variables in previous tutorials. Put the timeLeft declaration right after the other
declarations. Your code should look like the following sample.
C#
C#
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
3. On the form, select the timer1 icon that you just added, and set its Interval
property to 1000. Because this interval is in milliseconds, a value of 1000 causes the
timer to raise a Tick event every second.
Before you write that event handler, add a method called CheckTheAnswer() to
determine whether the answers to the math problems are correct. This method should
be in line with the other methods, such as StartTheQuiz() . Your code should look like
the following sample.
C#
C#
/// <summary>
/// Check the answers to see if the user got everything right.
/// </summary>
/// <returns>True if the answer's correct, false otherwise.</returns>
private bool CheckTheAnswer()
{
if ((addend1 + addend2 == sum.Value)
&& (minuend - subtrahend == difference.Value)
&& (multiplicand * multiplier == product.Value)
&& (dividend / divisor == quotient.Value))
return true;
else
return false;
}
This method determines the answers to the math problems and compares the results to
the values in the NumericUpDown controls. In this code:
The Visual Basic version uses the Function keyword instead of the usual Sub
keyword because this method returns a value.
You can't easily enter the multiplication sign (×) and the division sign (÷) by using
the keyboard, so C# and Visual Basic accept an asterisk (*) for multiplication and a
slash mark (/) for division.
In C#, && is the logical and operator. In Visual Basic, the equivalent operator is
AndAlso . You use the logical and operator to check whether more than one
condition is true. In this case, if the values are all correct, the method returns a
value of true . Otherwise, the method returns a value of false .
1. On the form, double-click the Timer control, or select it and then select Enter.
These actions add a Tick event handler to the timer. The code editor appears and
displays the Tick handler's method.
C#
C#
Each second of the quiz, this method runs. The code first checks the value that
CheckTheAnswer() returns.
If all answers are correct, that value is true , and the quiz ends:
The timer stops.
A congratulatory message appears.
The Enabled property of the startButton control is set to true so that the quiz
taker can start another quiz.
C#
C#
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);
When your quiz starts, this code sets the timeLeft variable to 30 and the Text property
of the timeLabel control to 30 seconds. Then the Start() method of the Timer control
starts the countdown.
Run your app
1. Save your program and run it.
2. Select Start the quiz. The timer starts to count down. When time runs out, the quiz
ends, and the answers appear.
3. Start another quiz, and provide correct answers to the math problems. When you
answer correctly within the time limit, a message box opens, the start button
becomes available, and the timer stops.
Next steps
Advance to the next tutorial to learn how to customize your math quiz.
In this series of four tutorials, you'll build a math quiz. The quiz contains four random
math problems that a quiz taker tries to answer within a specified time.
This tutorial shows you how to enhance your quiz by clearing default values and by
customizing the appearance of controls.
Prerequisites
This tutorial builds on previous tutorials, starting with Create a math quiz WinForms app.
If you haven't completed those tutorials, go through them first.
1. Select the first NumericUpDown control on the form. In the Properties dialog box,
select the Events icon on the toolbar.
The Events tab in Properties displays all the events that you can respond to for the
item that you selected on the form. In this case, all the listed events pertain to the
NumericUpDown control.
2. Select the Enter event, enter answer_Enter, and then select Enter.
The code editor appears and displays the Enter event handler that you created for
the sum NumericUpDown control.
3. In the method for the answer_Enter event handler, add the following code:
C#
if (answerBox != null)
{
int lengthOfAnswer = answerBox.Value.ToString().Length;
answerBox.Select(0, lengthOfAnswer);
}
}
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
In this code:
The first line declares the method. It includes a parameter that's named sender . In
C#, the parameter is object sender . In Visual Basic, it's sender As System.Object .
This parameter refers to the object whose event is firing, which is known as the
sender. In this case, the sender object is the NumericUpDown control.
The first line inside the method casts, or converts, the sender from a generic object
to a NumericUpDown control. That line also assigns the name answerBox to the
NumericUpDown control. All the NumericUpDown controls on the form will use
this method, not just the addition problem's control.
The next line verifies whether answerBox was successfully cast as a
NumericUpDown control.
The first line inside the if statement determines the length of the answer that's
currently in the NumericUpDown control.
The second line inside the if statement uses the answer length to select the
current value in the control.
When the quiz taker selects the control, Visual Studio fires this event. This code selects
the current answer. As soon as the quiz taker starts to enter a different answer, the
current answer is cleared and replaced with the new answer.
2. In the Events page of the Properties dialog box, find the Click event, and then
select answer_Enter from the drop-down menu. This event handler is the one that
you just added.
4. In the Events page of the Properties dialog box, find the Enter event, and then
select answer_Enter from the drop-down menu. This event handler is the one that
you just added. Repeat this step for the Click event.
5. Repeat the previous two steps for the multiplication and division NumericUpDown
controls.
C#
timeLabel.BackColor = Color.Red;
Next steps
Congratulations! You've finished this series of tutorials. You've completed these
programming and design tasks in the Visual Studio IDE:
Continue learning with another tutorial series on how to build a matching game.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches
pairs of hidden icons.
Use these tutorials to learn about the following tasks in the Visual Studio Integrated
Design Environment (IDE).
Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads
page for a free version.
3. On the Create a new project window, search for Windows Forms. Then select
Desktop from the All project types list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual
Basic, and then select Next.
7 Note
If you don't see the Windows Forms App (.NET Framework) template, you
can install it from the Create a new project window. In the Not finding what
you're looking for? message, select the Install more tools and features link.
Select Modify in the Visual Studio Installer. You might be prompted to save
your work. Next, select Continue to install the workload.
5. In the Configure your new project window, name your project MatchingGame,
then select Create.
Visual Studio creates a solution for your app. A solution is a container for all of the
projects and files needed by your app.
At this point, Visual Studio displays an empty form in the Windows Form Designer.
1. Click on the form to select the Windows Forms Designer. The tab reads Form1.cs
[Design] for C# or Form1.vb [Design] for Visual Basic. In the Properties window,
set the following form properties.
Change the Text property from Form1 to Matching Game. This text appears
at the top of the game window.
Set the size of the form. You can change it either by setting the Size property
to 550, 550, or by dragging the corner of the form until you see the correct
size at the bottom of the Visual Studio IDE.
2. Select the Toolbox tab on the left side of the IDE. If you don't see it, select View >
Toolbox from the menu bar or Ctrl+Alt+X.
7 Note
The colors are not in alphabetical order, and CornflowerBlue is near the
bottom of the list.
Set the Dock property to Fill from the dropdown list by selecting the large
middle button. This option spreads the table out so that it covers the entire
form.
Set the CellBorderStyle property to Inset. This value provides visual borders
between each cell on the board.
On the task menu, select Edit Rows and Columns to open the Column and
Row Styles window. For each column, select the Percent option, and then set
each column's width to 25 percent.
Select Rows from the list at the top of the window, and then set each row's
height to 25 percent.
When you're done, select OK to save your changes.
1. Be certain that the TableLayoutPanel is selected in the form editor. You should see
tableLayoutPanel1 at the top of the Properties window. If it isn't selected, select
the TableLayoutPanel on the form, or select it from the list at the top of the
Properties window.
2. Open the toolbox, as before, and open the Common Controls category. Add a
Label control to the upper-left cell of the TableLayoutPanel. The label control is
now selected in the IDE. Set the following properties for it.
Set the BackColor property of the label to CornflowerBlue.
Set the AutoSize property to False.
Set the Dock property to Fill.
Set the TextAlign property to MiddleCenter by choosing the drop-down
button next to the property, and then selecting the middle button. This value
ensures the icon appears in the middle of the cell.
Select the Font property. An ellipsis (...) button appears. Select the ellipsis and
set the Font value to Webdings, the Font Style to Bold, and the Size to 48.
Set the Text property of the label to the letter c.
The upper-left cell of the TableLayoutPanel now contains a black box centered on a
blue background.
7 Note
Webdings is a font of icons that ships with the Windows operating system. In
your matching game, the player matches pairs of icons. This font displays the
icons to match.
3. Select your Label control and copy it to the next cell in the TableLayoutPanel.
Select the Ctrl+C keys, or on the menu bar, Edit > Copy. Then paste it by using
Ctrl+V or Edit > Paste.
A copy of the first Label appears in the second cell of the TableLayoutPanel. Paste it
again, and another Label appears in the third cell. Keep pasting Label controls until
all of the cells are filled.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches
pairs of hidden icons.
In the matching game, a player selects a square to see an icon, then chooses another
square. If the icons match, they stay visible. If not, the game hides both icons. In this
tutorial, you assign icons to labels randomly. You set them to be hidden and then
displayed when selected.
Prerequisites
This tutorial builds on the previous tutorial, Create a matching game application. If you
haven't done that tutorial, go through that one first.
You use new statements to create two objects. The first is a Random object that
randomly chooses cells in the TableLayoutPanel. The second object is a List<T> object. It
stores the randomly chosen symbols.
1. Open Visual Studio. Your MatchingGame project appears under Open recent.
2. Select Form1.cs if you're using C#, or Form1.vb if you're using Visual Basic. Then
select View > Code. As an alternative, select the F7 key or double-click Form1. The
Visual Studio IDE displays the code module for Form1.
C#
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
If you're using C#, be sure you put the code after the opening curly brace and just after
the class declaration ( public partial class Form1 : Form ). If you're using Visual Basic,
put the code right after the class declaration ( Public Class Form1 ).
You can use list objects to keep track of different types of items. A list can hold numbers,
true/false values, text, or other objects. In your matching game, the list object has 16
strings, one for each cell in the TableLayoutPanel panel. Each string is a single letter that
corresponds to the icons in the labels. These characters appear in the Webdings font as
a bus, a bike, and others.
7 Note
Lists can shrink and grow as needed, which is important in this program.
To learn more about lists, see List<T>. To see an example in C#, see A basic list example.
To see an example in Visual Basic, see Using a Simple Collection.
C#
C#
/// <summary>
/// Assign each icon from the list of icons to a random square
/// </summary>
private void AssignIconsToSquares()
{
// The TableLayoutPanel has 16 labels,
// and the icon list has 16 icons,
// so an icon is pulled at random from the list
// and added to each label
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;
if (iconLabel != null)
{
int randomNumber = random.Next(icons.Count);
iconLabel.Text = icons[randomNumber];
// iconLabel.ForeColor = iconLabel.BackColor;
icons.RemoveAt(randomNumber);
}
}
}
You can enter this code just below the code you added in the previous section.
7 Note
One of the lines is commented out on purpose. You add it later in this procedure.
The first line converts the control variable to a label named iconLabel.
The second line is an if statement that checks to make sure the conversion
worked. If the conversion does work, the statements in the if statement run.
The first line in the if statement creates a variable named randomNumber that
contains a random number that corresponds to one of the items in the icons list. It
uses the Next() method of the Random object. The Next method returns the
random number. This line also uses the Count property of the icons list to
determine the range from which to choose the random number.
The next line assigns one of the icons list items to the Text property of the label.
The next line hides the icons. The line is commented out here so you can verify the
rest of the code before proceeding.
The last line in the if statement removes the icon that has been added to the
form from the list.
C#
public Form1()
{
InitializeComponent();
AssignIconsToSquares();
}
For Visual Basic, add the AssignIconsToSquares() method call to the Form1_Load
method.
VB
2. Save your program and run it. It should show a form with random icons assigned
to each label.
Tip
If the Webdings icons don't display properly on the form, set the
UseCompatibleTextRendering property of labels on the form to True.
3. Close your program, and then run it again. Different icons are assigned to each
label.
The icons are visible now because you haven't hidden them. To hide them from the
player, you can set each label's ForeColor property to the same color as its
BackColor property.
4. Stop the program. Remove the comment marks for the commented line of code
inside the loop.
C#
C#
iconLabel.ForeColor = iconLabel.BackColor;
If you run the program again, the icons seem to have disappeared. Only a blue
background appears. The icons are randomly assigned and are still there.
To get your game to work this way, add a Click event handler that changes the color of
the chosen label to match the background.
1. Open the form in the Windows Forms Designer. Select Form1.cs or Form1.vb, and
then select View > Designer.
2. Choose the first label control to select it and double-click it to add a Click event
handler called label1 _Click() to the code.
3. Then, hold the Ctrl key while you select each of the other labels. Be sure that every
label is selected.
4. In the Properties window, select the Events button, which is a lightening bolt. For
the Click event, select label1_Click in the box.
5. Select the Enter key. The IDE adds a Click event handler called label1 _Click() to
the code. Because you selected all the labels, the handler is hooked to each of the
labels.
C#
C#
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;
clickedLabel.ForeColor = Color.Black;
}
}
7 Note
If you copy and paste the label1_Click() code block rather than entering the code
manually, be sure to replace the existing label1_Click() code. Otherwise, you'll
end up with a duplicate code block.
Select Debug > Start Debugging to run your program. You should see an empty form
with a blue background. Choose any of the cells in the form. One of the icons should
become visible. Continue choosing different places in the form. As you choose the icons,
they should appear.
Next steps
Advance to the next tutorial to learn how to change labels using a timer.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches
pairs of hidden icons.
Your Matching Game program needs to track which Label controls the player chooses.
After a player chooses the first label, the program should show the icon. After the
second label is chosen, the program should display both icons for a brief time. Then it
hides both icons.
Your program keeps track of which Label you choose first and second by using reference
variables. A timer hides the icons and controls how long to show the icons
Prerequisites
This tutorial builds on previous tutorials, Create a matching game application and Add
icons to your matching game. Complete those tutorials first.
C#
C#
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
These statements don't cause Label controls to appear on the form because there's no
new keyword. When the program starts, both firstClicked and secondClicked are set
2. Modify your Click event handler to use the new firstClicked reference variable.
Remove the last statement in the label1_Click() event handler method
( clickedLabel.ForeColor = Color.Black; ) and replace it with the if statement as
follows.
C#
C#
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;
return;
}
}
}
3. Save and run your program. Choose one of the label controls, and its icon appears.
Choose the next label control, and notice that nothing happens.
Only the first icon that's chosen appears. The other icons are invisible.
The program is already keeping track of the first label that the player chose. The
reference firstClicked isn't null in C# or Nothing in Visual Basic. When your if
statement finds that firstClicked isn't equal to null or Nothing , it runs the statements.
Add a timer
The Matching Game app uses a Timer control. A timer waits, and then fires an event,
referred to as a tick. A timer can start an action or repeat an action regularly.
In your program, the timer enables a player to choose two icons. If the icons don't
match, it hides the two icons again after a short period of time.
1. Select the Toolbox tab, in the Components category, double-click or drag the
Timer component to your form. The timer icon, called timer1, appears in a space
below the form.
2. Select the Timer1 icon to select the timer. In the Properties window, select the
Properties button to view properties.
The Interval property tells the timer how long to wait between ticks, when it
triggers its Tick event. Your program calls the Start() method to start the timer after
the player chooses the second label.
4. Choose the timer control icon and then press Enter, or double-click the timer. The
IDE adds an empty Tick event handler. Replace the code with the following code.
C#
C#
/// <summary>
/// This timer is started when the player clicks
/// two icons that don't match,
/// so it counts three quarters of a second
/// and then turns itself off and hides both icons
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
// Stop the timer
timer1.Stop();
It makes sure the timer isn't running by calling the Stop() method.
It uses two reference variables, firstClicked and secondClicked , to make the
icons of the two labels that the player chose invisible again.
It resets the firstClicked and secondClicked reference variables to null in C#
and Nothing in Visual Basic.
5. Go to the code editor and add code to the top and bottom of the label1_Click()
event handler method. This code will check if the timer is enabled, set the
secondClicked reference variable, and start the timer. The label1_Click() event
handler method now looks as follows:
C#
C#
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
// The timer is only on after two non-matching
// icons have been shown to the player,
// so ignore any clicks if the timer is running
if (timer1.Enabled == true)
return;
if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;
The code at the top of the method checks whether the timer was started by
checking the value of the Enabled property. If the player chooses the first and
second Label controls and the timer starts, choosing a third label won't do
anything.
The code at the bottom of the method sets the secondClicked reference variable
to track the second Label control. Then, it sets that label icon color to black to
make it visible. Then, it starts the timer in one-shot mode, so that it waits 750
milliseconds and then fires a single tick. The timer's Tick event handler hides the
two icons and resets the firstClicked and secondClicked reference variables. The
form is ready for the player to choose another pair of icons.
7 Note
If you copy and paste the label1_Click() code block rather than entering the code
manually, be sure to replace the existing label1_Click() code. Otherwise, you'll
end up with a duplicate code block.
6. Save and run your program. Select a square and the icon becomes visible. Choose
another square. The icon appears briefly and then both icons disappear.
Your program now keeps track of the first and second icons that you choose. It uses the
timer to pause before making the icons disappear.
Next steps
Advance to the next tutorial to learn how to finish your Matching Game.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches
pairs of hidden icons.
In this tutorial, you revise your Matching Game to keep matched pairs visible and to
display a congratulations message when a player wins.
Prerequisites
This tutorial builds on these previous tutorials:
1. Add the following if statement to the label_Click() event handler method. Put it
near the end of the code just above the statement where you start the timer.
C#
C#
// If the player gets this far, the timer isn't
// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;
) Important
Use the programming language control at the top right of this page to view either
the C# code snippet or the Visual Basic code snippet.
The if statement checks whether the icon in the first label that the player chooses is
the same as the icon in the second label. If the icons are the same, the program runs its
three statements. The first two statements reset the firstClicked and secondClicked
reference variables. They no longer keep track of any of the labels. The third statement
is a return statement, which skips the rest of the statements in the method without
running them.
2. Run the program, and then start choosing squares on the form.
If you choose a pair that doesn't match, the timer's Tick event triggers. Both icons
disappear.
If you choose a matching pair, the new if statement runs. The return statement causes
the method to skip the code that starts the timer. The icons stay visible.
C#
C#
/// <summary>
/// Check every icon to see if it is matched, by
/// comparing its foreground color to its background color.
/// If all of the icons are matched, the player wins
/// </summary>
private void CheckForWinner()
{
// Go through all of the labels in the TableLayoutPanel,
// checking each one to see if its icon is matched
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;
if (iconLabel != null)
{
if (iconLabel.ForeColor == iconLabel.BackColor)
return;
}
}
The method uses another foreach loop in C# or For Each loop in Visual Basic to go
through each label in the TableLayoutPanel. It checks each label's icon color to verify
whether it matches the background. If the colors match, the icon remains invisible, and
the player hasn't matched all of the remaining icons.
In that case, the program uses a return statement to skip the rest of the method. If the
loop gets through all of the labels without executing the return statement, that means
that all of the icons on the form were matched. The program shows a MessageBox to
congratulate the player on winning, and then calls the Close() method to end the
game.
2. Have the label's Click event handler call the new CheckForWinner() method.
C#
C#
Be sure that your program checks for a winner immediately after it shows the second
icon that the player chooses. Look for the line where you set the second chosen icon's
color, and then call the CheckForWinner() method right after that line.
3. Save and run the program. Play the game and match all of the icons. When you
win, the program displays a congratulatory message.
After you select OK, the Matching Game closes.
Add a game timer that tracks how long it takes for the player to win.
You can add a label to display the elapsed time on the form. Place it above the
TableLayoutPanel. Add another timer to the form to track the time. Use code to
start the timer when the player starts the game, and stop the timer after they
match the last two icons.
Add a sound when the player finds a match, another sound when the player
uncovers two icons that don't match, and a third sound when the program hides
the icons again.
To play sounds, you can use the System.Media namespace. For more information,
see Play sounds in Windows Forms app (C#) or How to play audio in Visual
Basic .
You'll need to do more than just add rows and columns to the TableLayoutPanel.
You also need to consider the number of icons you create.
Make the game more challenging by hiding the first icon if the player is too slow
to respond.
Next steps
Congratulations! You've completed this series of tutorials. You've done these
programming and design tasks in the Visual Studio IDE:
Advance to this article for a deep dive into Windows Forms Designer.
How to run a program depends on what you start from, the type of program, and
whether you want to run under the debugger. In the simplest case, to build and run an
open project in Visual Studio:
Press F5, choose Debug > Start with debugging from the Visual Studio menu, or
select the green Start arrow and project name on the Visual Studio toolbar.
Or, to run without debugging, press Ctrl+F5 or choose Debug > Start without
debugging from the Visual Studio menu.
1. If your program code is already in a Visual Studio project, open the project. To do
so, you can double-click or tap on the .csproj file in Windows File Explorer, or
choose Open a project in Visual Studio, browse to find the .csproj file, and select
the file.
2. After the project loads in Visual Studio, if your Visual Studio solution has more
than one project, make sure to set the project with the Main method as the startup
project. To set the startup project, right-click on the project name or node in
Solution Explorer and choose Set as Startup Project from the context menu.
3. To run the program, press Ctrl+F5, select Debug > Start without debugging from
the top menu, or select the green Start button.
Visual Studio tries to build and run your project. At the bottom of the Visual Studio
screen, the build output appears in the Output window, and any build errors
appear in the Error List window.
If the build succeeds, the app runs as appropriate for the type of project. Console
apps run in a terminal window, Windows desktop apps start in a new desktop
window, and web apps run in a browser hosted by IIS Express.
Application template to create a project to work with the app in Visual Studio.
If the code is from another development environment, there's no project file. Open the
folder by choosing Open > Folder in Visual Studio. See Develop code without projects
or solutions.
Visual Studio attempts to build and run the code in your project. If a build doesn't
succeed, see the following sections for some ideas on how to get the project to build
successfully.
Troubleshooting
Your code might have errors. Or the code might be correct, but maybe it depends on
missing assemblies or NuGet packages, or targets a different version of .NET. In those
cases, you might be able to easily fix the build.
Add references
To build properly, the code must be correct and have the right references to libraries or
other dependencies. Red squiggly underlines in code or entries in the Error List show
errors even before you compile and run the program. If the errors relate to unresolved
names, you probably need to add a reference or a using directive, or both. If the code
references any missing assemblies or NuGet packages, you need to add those
references to the project.
Visual Studio tries to help you identify missing references. When a name is unresolved, a
light bulb icon appears in the editor. Select the light bulb to see suggestions on how to
fix the issue. Fixes might be to:
Here's an example of a missing using directive. You can add using System; to the start
of the code file to resolve the unresolved name Console :
More recent of C# support implicit using directives for some commonly used
namespaces, so if you chose that option when creating a project, you don't need them.
You can find assemblies and add references by following the instructions in Add or
remove references by using the Reference Manager.
Add a NuGet package
If Visual Studio detects a missing NuGet package, a light bulb appears and gives you the
option to install the package:
If that doesn't solve the issue or Visual Studio can't locate the package, try searching for
the package online. See Install and use a NuGet package in Visual Studio.
To change the target .NET Framework version, see Change the target framework. For
more information, see Troubleshooting .NET Framework targeting errors.
Next steps
Explore the Visual Studio development environment by reading Welcome to the
Visual Studio IDE.
Create your first C# app.
Tutorial: Open a project from a repo
Article • 12/05/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, you'll use Visual Studio to connect to a repository for the first time, clone
it, 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.
Here's how.
3. Enter or type the repository location, and then select the Clone button.
4. If you're not already signed in, you might be prompted to sign into Visual Studio
or your GitHub account.
Tip
For more information about signing in to Visual Studio, see the Sign in to
Visual Studio page. For specific information about how to use your GitHub
account to sign in, see the Work with GitHub accounts in Visual Studio page.
And if you receive a trust notification and want to know more about it, see the
Configure trust settings for files and folders page.
Or, you can select the Switch Views button, and then select Program.cs to view a
solution's code.
Tip
You can change from the default Folder View to Solution View from the Git menu.
Select Settings > Source Control > Git Global Settings > Automatically load the
solution when opening a Git repository to do so.
Open a project locally from a previously cloned GitHub repo
1. Open Visual Studio.
Visual Studio opens an instance of File Explorer, where you can browse to your
solution or project, and then select it to open it.
Tip
If you've opened the project or solution recently, select it from the Open
recent section to quickly open it again.
Start coding!
Here's how.
2. Follow the prompts to connect to the Git repository that includes the files you're
looking for.
1. In the Visual Studio IDE, select the Git menu, select Local Repositories, and then
select Open Local Repository.
2. Follow the prompts to connect to the Git repository that has the files you're
looking for.
4. Follow the prompts to clone an Azure DevOps repo that includes the files you're
looking for, and then open your project.
Next steps
Feel free to 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
Visual Studio version control documentation
Learn to use the code editor with C#
Article • 09/01/2022
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
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.
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.
1. Open Visual Studio. Press Esc, or choose Continue without code on the start
window, to open the development environment.
2. From the File menu on the menu bar, choose New > File, or press Ctrl+N.
3. In the New File dialog box, under the General category, choose Visual C# Class,
and then choose Open.
A new file opens in the editor with the skeleton of a C# class. You don't have to
create a full Visual Studio project to gain some of the benefits that the code editor
offers—all you need is a code file.
Use code snippets
Visual Studio provides useful code snippets that you can use to quickly and easily
generate commonly used code blocks. Code snippets are available for different
programming languages including C#, Visual Basic, and C++.
1. Place your cursor just above the final closing brace } in the file, and type the
characters svm . svm stands for static void Main —don't worry if you don't know
what that means yet.
A pop-up dialog box appears with information about the svm code snippet.
Available code snippets vary for different programming languages. You can look at the
available code snippets for your language by choosing Edit > IntelliSense > Insert
Snippet or pressing Ctrl+K, Ctrl+X, and then choosing the folder for your programming
language. For C#, the snippet list looks like this:
The list includes snippets for creating a class, a constructor, a for loop, an if or switch
statement, and more.
C#
// someWords is a string array.
string[] someWords = {
"the",
"quick",
"brown",
"fox",
"jumps"
};
string[] moreWords = {
"over",
"the",
"lazy",
"dog"
};
2. We're not using the moreWords variable, but we might use it later so we don't want
to delete it. Instead, we'll comment out those lines. Select the entire definition of
moreWords down to the closing semicolon, and then choose the Comment out the
selected lines button on the toolbar. If you prefer to use the keyboard, press
Ctrl+E, Ctrl+C.
The C# comment characters // are added to the beginning of each selected line
to comment out the code.
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 peek definition window by choosing the small box with an "x" at the top
right of the pop-up window.
Let's add a line of code to print out the ordered strings to the console window, which is
the standard place for output from the program to go.
C#
You'll see an IntelliSense pop-up appear with information about the query symbol.
2. To insert the rest of the word query by using IntelliSense word completion, press
Tab.
3. Finish off the code block to look like the following code. You can practice further
with code snippets by entering cw and then pressing Tab twice to generate the
Console.WriteLine statement.
C#
Refactor a name
Nobody gets code right the first time, and one of the things you might have to change
is the name of a variable or method. Let's try out Visual Studio's refactor functionality to
rename the someWords variable to unsortedWords .
1. Place your cursor over the definition of the someWords variable, and choose
Rename from the right-click or context menu, or press F2.
2. Enter the desired name unsortedWords. You'll see that the reference to
unsortedWords in the query assignment statement is also automatically renamed.
Before you press Enter, select the Include comments checkbox in the Rename
pop-up box.
Both occurrences of someWords in your code have been renamed, as well as the
text someWords in your 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
Article • 01/18/2024
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:
ノ Expand table
The documentation in this section goes into further details of the IDE-based build
process. For more information on the other methods, see CMake, MSBuild and Azure
Pipelines, respectively.
Next, see Building and cleaning projects and solutions in Visual Studio to learn about
the different customizations you can make to the process. Customizations include
changing output directories, specifying custom build events, managing project
dependencies, managing build log files, and suppressing compiler warnings.
Related content
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
Article • 10/25/2023
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article introduces the features of the Visual Studio debugger in a step-by-step
walkthrough. If you want a higher-level view of the debugger features, see First look at
the debugger. When you debug your app, it usually means that you're running your
application with the debugger attached. When you do this task, the debugger provides
many ways to see what your code is doing while it runs. You can step through your code
and look at the values stored in variables, you can set watches on variables to see when
values change, you can examine the execution path of your code, see whether a branch
of code is running, and so on. If this exercise is the first time that you've tried to debug
code, you might want to read Debugging for absolute beginners before going through
this article.
Although the demo app is C#, most of the features are applicable to C++, Visual Basic,
F#, Python, JavaScript, and other languages supported by Visual Studio (F# doesn't
support Edit-and-continue. F# and JavaScript don't support the Autos window). The
screenshots are in C#.
Prerequisites
You must have Visual Studio 2022 installed and the .NET desktop development
workload.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page
to install it for free.
If you already have Visual Studio but the .NET desktop development workload isn't
installed, go to Tools > Get Tools and Features..., which launches the Visual Studio
Installer. In the Visual Studio Installer, choose the .NET desktop development workload,
then choose Modify.
Create a project
First, you create a .NET Core console application project. The project type comes with all
the template files you need, before you've even added anything!
1. Open Visual Studio. If the start window isn't open, select File > Start Window.
3. On the Create a new project window, enter 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
template, and then select Next.
7 Note
If you don't see the Console App 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 desktop development workload.
C#
using System;
class ArrayExample
{
static void Main()
{
char[] letters = { 'f', 'r', 'e', 'd', ' ', 's', 'm', 'i', 't', 'h'};
string name = "";
int[] a = new int[10];
for (int i = 0; i < letters.Length; i++)
{
name += letters[i];
a[i] = i + 1;
SendMessage(name, a[i]);
}
Console.ReadKey();
}
1. To start the debugger, select F5, or choose the Debug Target button in the
Standard toolbar, or choose the Start Debugging button in the Debug toolbar, or
choose Debug > Start Debugging from the menu bar.
F5 starts the app with the debugger attached to the app process. Since we haven't
done anything special to examine the code, the app runs to completion and you
see the console output.
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
2. To stop the debugger, select Shift+F5, or choose the Stop Debugging button in
the Debug toolbar, or choose Debug > Stop Debugging from the menu bar.
3. In the console window, select any key to close the console window.
name += letters[i];
Breakpoints are an essential feature of reliable debugging. You can set breakpoints
where you want Visual Studio to pause your running code so you can look at the
values of variables or the behavior of memory, or know whether or not a branch of
code is getting run.
2. To start debugging, select F5, or choose the Debug Target button in the Standard
toolbar, or choose the Start Debugging button in the Debug toolbar, or choose
Debug > Start Debugging from the menu bar. The app starts and the debugger
runs to the line of code where you set the breakpoint.
The yellow arrow points to the statement on which the debugger paused. App
execution is paused at the same point, with the statement not yet executed.
When the app isn't running, F5 starts the debugger, which runs the app until it
reaches the first breakpoint. If the app is paused at a breakpoint, then F5 will
continue running the app until it reaches the next breakpoint.
Breakpoints are a useful feature when you know the line or section of code that
you want to examine in detail. For more about the different types of breakpoints
you can set, such as conditional breakpoints, see Using breakpoints.
7 Note
One of the most useful features of the debugger is its ability to inspect a
variable. Often, when you're trying to debug an issue, you're attempting to
find out whether variables have values that you expect at a particular time.
Viewing data tips is a good way to check that.
2. Expand the letters variable to view all its array elements and their values.
3. Hover over the name variable to see its current value, which is an empty string.
4. To advance the debugger to the next statement, select F10, or choose the Step
Over button in the Debug toolbar, or choose Debug > Step Over from the menu
bar. Select F10 twice more to move past the SendMessage method call.
F10 advances the debugger without stepping into function or methods, although
their code still executes. In this way, we skipped debugging the code in the
SendMessage method, which we're not interested in right now.
5. To iterate through the for loop a few times, select F10 repeatedly. During each
loop iteration, pause at the breakpoint, and then hover over the name variable to
check its value in the data tip.
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, select F5 instead, which advances to your breakpoint instead of the
next statement.
6. While code execution is paused in the for loop of the Main method, select F11, or
choose the Step Into button from the Debug toolbar, or choose Debug > Step
Into from the menu bar, until you reach the SendMessage method call.
F11 helps you examine the execution flow of your code in more depth. To step into
a method from a method call, select F11. By default, the debugger skips stepping
into nonuser methods. To learn about debugging nonuser code, see Just My Code.
Once you've finished debugging the SendMessage method, you're ready to return
to the for loop of the main method.
8. To leave the SendMessage method, select Shift+F11, or choose the Step Out button
in the Debug toolbar, or choose Debug > Step Out from the menu bar.
Step Out resumes app execution and advances the debugger until the current
method or function returns.
You see the yellow pointer back in the for loop of the Main method, paused at the
SendMessage method call. For more information on different ways to move through
2. In the code editor, hover over the Console.WriteLine method call in the
SendMessage method until the Run to Click button appears. The tooltip for the
method call, and choose Run to Cursor from the context menu.
Using the Run to Click button is similar to setting a temporary breakpoint, and is
handy for getting around quickly within a visible region of your app code in an
open file.
Restart stops the debugger and then restarts it, in one step. When the debugger
restarts, it runs to the first breakpoint, which is the breakpoint you previously set inside
the for loop, and then pause.
If the Autos window is closed, select Ctrl+D, A, or choose Debug > Windows >
Autos from the menu bar.
2. With the debugger still paused, view the Locals window, in a tab next to the Autos
window.
If the Locals window is closed, select Ctrl+D, L, or choose Debug > Windows >
Locals.
3. In the Locals window, expand the letters variable to see its array elements and
their values.
For more about the Autos and Locals windows, see Inspect variables in the Autos and
Locals windows.
Set a watch
You can specify a variable, or an expression, that you want to keep an eye on as you step
through code—by adding it to the Watch window.
1. While the debugger is paused, right-click the name variable and choose Add
Watch.
The Watch window opens by default at the bottom of the code editor.
2. Now that you've set a watch on the name variable, step through your code to see
the value of the name variable change with each for loop iteration.
Unlike the other variable windows, the Watch window always shows the variables
that you're watching. Variables that are out of scope are displayed as unavailable.
For more information about the Watch window, see Watch variables with Watch
windows.
1. While the debugger is paused in the for loop, view the Call Stack window, which
opens by default in the lower right pane of the code editor.
If the Call Stack window is closed, select Ctrl+D, C, or choose Debug > Windows >
Call Stack from the menu bar.
In the Call Stack window, you see the yellow pointer at the current Main method.
2. Select F11 a few times until you see the debugger pause in the SendMessage
method.
The top line of the Call Stack window shows the current function, which is the
SendMessage method. The second line shows that the SendMessage method was
7 Note
The Call Stack window is similar to the Debug perspective in some IDEs, like
Eclipse.
In the Call Stack window, you can double-click a line of code to go to that source
code, which changes the current scope under inspection by the debugger. This
action doesn't 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 by using Run to Cursor, or go to source code.
For more about the Call Stack, see How to: Examine the Call Stack.
1. With the debugger paused at the SendMessage method call in the for loop, select
F11 three times to step into the SendMessage method and to move past the
Console.WriteLine method after executing it.
The debugger is now paused at the final closing brace of the SendMessage method.
2. Use the mouse to grab the yellow arrow or execution pointer (in the left margin),
and then drag the pointer up one line.
3. Select F11.
The debugger reruns the Console.WriteLine method, and you see a duplicate line
in the console window output.
By changing the execution flow, you can do things like test different code execution
paths or rerun code without restarting the debugger.
2 Warning
Use this feature with care. You'll see a warning in the tooltip of the execution
pointer about the possibility of unintended consequences. You might see other
warnings, too. Moving the execution pointer can't revert your application to an
earlier state.
For more about the changing the execution flow, see Move the pointer to change the
execution flow.
Next steps
In this tutorial, you've learned how to start the debugger, step through code, and
inspect variables. You might want to get a high-level look at debugger features along
with links to more information.
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.
In this article, the code uses C# and C++, illustrations are in C#, but the concepts and
features apply to .NET languages, C++, Python, JavaScript, and TypeScript.
For the purposes of demonstrating an example unit test, this article tests a simple
"Hello World" C# or C++ Console project named HelloWorld. The sample code for
such a project is as follows:
.NET
C#
namespace HelloWorld
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
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 the unit test project to use.
Type test in the search box to find a unit test project template for the test
framework you want to use, such as MSTest (C#) or the Native Unit Test project
(C++), and select it.
Starting in Visual Studio 2017 version 14.8, the .NET languages include built-in
templates for NUnit and xUnit. For C++, in this example select the Native Unit Test
project, which uses Microsoft Native Unit Test Framework. (To use a different C++
test framework, see Writing unit tests for C/C++). For Python, see Set up unit
testing in Python code to set up your test project.
Tip
For C# only, you can create unit test projects from code using a faster
method. For more information, see Create unit test projects and test
methods. To use this method with .NET Core or .NET Standard, Visual Studio
2019 or later is required.
The following illustration shows an MSTest unit test, which is supported in .NET.
Click Next, choose a name for the test project, and then click Create.
5. Select the project that contains the code you'll test and click OK.
For example, you might use the following code by selecting the correct
documentation tab that matches your test framework: MSTest, NUnit, or xUnit
(supported on .NET only), or C++ Microsoft Native Unit Test Framework.
MSTest
C#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System;
namespace HelloWorldTests
{
[TestClass]
public class UnitTest1
{
private const string Expected = "Hello World!";
[TestMethod]
public void TestMethod1()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw);
HelloWorld.Program.Main();
To open Test Explorer, choose Test > Test Explorer from the top menu bar (or press
Ctrl + E, T).
2. Run your unit tests by clicking Run All (or press Ctrl + R, V).
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.
7 Note
To follow these steps, Visual Studio Enterprise is required, along with .NET code and
one of the following test frameworks: MSTest, xUnit, or NUnit.
1. Turn live unit testing from the Test menu by choosing Test > Live Unit Testing >
Start.
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.
Use the NuGet Package Manager to install the NuGet package for the framework
of your choice.
(.NET) Starting in Visual Studio 2017 version 14.6, Visual Studio includes pre-
configured test project templates for NUnit and xUnit test frameworks. The
templates also include the necessary NuGet packages to enable support.
(C++) In Visual Studio 2017 and later versions, some frameworks like Google C++
Testing Framework are already included. For more information, see Write unit tests
for C/C++ in Visual Studio.
1. Open the solution that contains the code you want to test.
2. Right-click on the solution in Solution Explorer and choose Add > New Project.
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.)
6. Run the test from Test Explorer or by right-clicking on the test code and choosing
Run Test(s) (or Ctrl + R, T).
Next steps
Unit test basics
About deployment
e OVERVIEW
Overview of Publish
g TUTORIAL
Publish tool
C++ applications
c HOW-TO GUIDE
Installer package
Setup project
g TUTORIAL
Publish tool
ClickOnce
Installer package
c HOW-TO GUIDE
g TUTORIAL
ClickOnce
Installer package
Deploy to Azure
g TUTORIAL
Azure Functions
c HOW-TO GUIDE
c HOW-TO GUIDE
Containerized apps
7 Note
Datasets and related classes are legacy .NET Framework technologies from the
early 2000s that enable applications to work with data in memory while the
applications are disconnected from the database. They are especially useful for
applications that enable users to modify data and persist the changes back to the
database. Although datasets have proven to be a very successful technology, we
recommend that new .NET applications use Entity Framework Core. Entity
Framework provides a more natural way to work with tabular data as object
models, and it has a simpler programming interface.
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 Server Object Explorer tool window in Visual Studio. In this topic, you create
an .mdf file and add tables and keys by using the Table Designer.
Prerequisites
To complete this walkthrough, you 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. See Modify Visual Studio.
7 Note
The procedures in this article apply only to .NET Framework Windows Forms
projects, not to .NET Core Windows Forms projects.
2. On the menu bar, select Project > Add New Item. If you see a small dialog box
with a box for a filename, choose Show All Templates.
3. In the list of item templates, scroll down and select Service-based Database.
3. On the Choose a Data Source Type page, choose Database and then choose Next.
4. On the Choose a Database Model page, choose Next to accept the default
(Dataset).
5. On the Choose Your Data Connection page, select the SampleDatabase.mdf file in
the drop-down list, and then choose Next.
6. On the Save the Connection String to the Application Configuration File page,
choose Next.
7. On the Choose your Database Objects page, you see a message that says the
database doesn't contain any objects. Choose Finish.
Select View > SQL Server Object Explorer (or Ctrl+\, Ctrl+S) to open the SQL
Server Object Explorer window. Expand (localdb)\MSSQLLocalDB > Databases,
and then right-click on SampleDatabase.mdf (it might be listed as a full path) and
select Properties.
Alternatively, you can select View > Server Explorer, if that window isn't already
open. Open the Properties window by expanding the Data Connections node,
right-clicking on SampleDatabase.mdf, and then selecting Properties.
Tip
To view the connection string, you can open the App.config file in Solution Explorer. You
should see an entry under the connectionStrings element that resembles the following
code:
XML
<connectionStrings>
<add
name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnection
String"
connectionString="Data Source=
(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;I
ntegrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The Table Designer opens and shows a grid with one default row, which represents
a single column in the table that you're creating. By adding rows to the grid, you
add columns in the table.
3. In the grid, add a row for each of the following entries:
ノ Expand table
4. Right-click on the CustomerID row, and then select Set Primary Key.
6. Name the Customers table by updating the first line in the script pane to match
the following sample:
SQL
7. Add an index constraint to the Customers table. Add a comma at the end of the
Phone line, then add the following sample before the closing parenthesis:
SQL
ノ Expand table
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:
SQL
SQL
The Orders table is created in the local database file. If you expand the Tables node
in Server Explorer, you see the two tables:
3. In the T-SQL pane, update the last line to match the following sample:
SQL
2. Open the shortcut menu for the Tables node, select Refresh, and then expand the
Tables node.
3. Open the shortcut menu for the Customers table, and then select Show Table Data
or View Data.
You can specify any five characters you want as the customer IDs, but choose at
least one that you can remember for use later in this procedure.
5. Open the shortcut menu for the Orders table, and then select Show Table Data or
View Data.
6. Add data for some orders. As you enter each row, it's saved in the database.
) 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.
Congratulations! You now know how to create tables, link them with a foreign key, and
add data.
Related content
Accessing data in Visual Studio