Visual Studio IDE
Visual Studio IDE
The Visual Studio interactive development environment (IDE) is a creative launching pad that you can use to view
and edit nearly any kind of code, and then debug, build, and publish apps for Android, iOS, Windows, the web, and
the cloud. There are versions available for Mac and Windows. This topic introduces you to the features of the
Visual Studio IDE. We'll walk through some things you can do with Visual Studio and how to install and use it,
create a simple project, get pointers on debugging and deploying code, and take a tour of the various tool
windows.
Or, you can simply open some code you get from almost anywhere and get working. See a project on GitHub that
you like? Just clone the repository, open it in Visual Studio, and start coding!
Create mobile apps
You can create native mobile apps for different platforms by using Visual C# and Xamarin, or Visual C++, or
hybrid apps using JavaScript with Apache Cordova. You can write mobile games for Unity, Unreal, DirectX, Cocos,
and more. Visual Studio includes an Android emulator to help you run and debug Android apps.
You can leverage the power of the cloud for your mobile apps by creating Azure app services. Azure app services
enable your apps to store data on the cloud, securely authenticate users, and automatically scale its resources up
or down to accommodate the needs of your app and your business. To learn more, see Mobile App Development.
Create cloud apps for Azure
Visual Studio offers a suite of tools that enable you to easily create cloud-enabled applications powered by
Microsoft Azure. You can configure, build, debug, package, and deploy applications and services on Microsoft
Azure directly from the IDE. Leverage Azure services for your apps using Connected Services. To get Azure Tools
for .NET, select the Azure development workload when you install Visual Studio. For more information, see
Visual Studio Tools for Azure.
Create apps for the web
The web drives our modern world, and Visual Studio can help you write apps for it. You can create web apps using
ASP.NET, Node.js, Python, JavaScript and TypeScript. Visual Studio understands web frameworks like Angular,
jQuery, Express, and more. ASP.NET Core and .NET Core run on Windows, Mac, and Linux operating systems. For
more information, see Modern Web Tooling.
Write code in a world class editing environment
Visual Studio helps you write code quickly and easily through features such as syntax colorization, statement
completion, IntelliSense (pop-up descriptions of the selected code element), code outlining, setting breakpoints for
debugging, and much more.
To learn more, see Writing Code in the Code and Text Editor.
Visual Studio can do help you do many more things. For a more complete list, see Visual Studio IDE.
Sign in
When you start Visual Studio for the first time, you can optionally sign in using your Microsoft account, or your
work or school account. Being signed in lets you synchronize Visual Studio settings, such as window layouts,
across multiple devices. It also connects you automatically to the services you might need, such as Azure
subscriptions and Visual Studio Team Services.
Create a program
One good way to learn about something is to use it! Let's dive in and create a new, simple program.
1. Open Visual Studio. On the menu, choose File, New, Project.
As an alternative, you can create a new project by using the Start Page. For more information, see Harness
the Power of the Redesigned Start Page (blog).
2. The New Project dialog box shows several project templates. Choose the Windows Universal category
under Visual C#, choose the Blank App (Universal Windows) template, and then choose the OK button.
This creates a new blank Universal Windows app project using Visual C# and XAML as the programming
languages. Wait for a bit while Visual Studio sets up the project for you. If you are prompted for any
information, just accept the default values for now.
3. In the New Universal Windows Project dialog box, accept the defaults by choosing OK.
4. Shortly, you should see something like the following screenshot. Your project files are listed on the right
side in a window called Solution Explorer.
5. In Solution Explorer, choose the little black triangle next to the MainPage.xaml file to expand it, and you
should see a MainPage.xaml.cs file underneath. Choose this file (which contains C# code) to open it.
The C# code in MainPage.xaml.cs appears in the code editor on the left side of the screen. Notice that the
code syntax is automatically colorized to indicate different types of code, such as statements or comments.
In addition, small, vertical dashed lines in the code indicate which braces match one another, and line
numbers help you locate code later. You can choose the small, boxed minus signs to collapse or expand
code. This code outlining feature lets you hide code you don't need, helping to minimize onscreen clutter.
There are other menus and tool windows available, but let's move on for now.
6. Add a button to the XAML form to give users a way to interact with your app. To do this, open the
MainPage.xaml file. This shows a split view: a designer above, for visually placing controls, and a code view
below, which shows the XAML code behind the designer. When you run the program later, what you see in
the designer becomes a window that users will see, a "form", and the underlying XAML determines what
appears on the form.
7. On the left side of the screen, choose the Toolbox tab to open the Toolbox. The Toolbox contains a number
of visual controls that you can add to forms. For now, we'll just add a button control.
8. Expand the Common XAML Controls section and then drag the Button control out to about the middle of
the form. (The exact location doesn't matter.)
When you're done, you should see something similar to the following.
The button is on the designer, and its underlying code (highlighted) is automatically added to the designer's
XAML code.
9. Let's change some of the XAML code. Rename the text in the button code from Button to Hello! .
10. Now, start the app. You can do this by choosing the Start ( ) button on the toolbar, or by choosing the F5
key, or on the menu, choosing Debug, Start Debugging.
The app begins its build process and status messages appear in the Output window. Soon, you should see
the form appear with your button in it. You now have a running app!
Of course, it doesn't do much right now, but you can add more functionality to it later if you want.
11. When you're done running the program, choose the Stop ( ) button on the toolbar to stop it.
Let's recap what you did so far: you created a new C# Windows Universal project in Visual Studio, viewed its code,
added a control to the designer, changed some XAML code, and then ran the project. Although the process was
simplified for this example, this shows you some common parts of the Visual Studio IDE that you will use when
you develop your own apps. If you want further details about this example, see Create a "Hello, world" app (XAML).
Refactoring includes operations such as intelligent renaming of variables, moving selected lines of code into
a separate function, moving code to other locations, reordering function parameters, and more.
IntelliSense is an umbrella term for a set of popular features that display type information about your
code directly in the editor and, in some cases, write small bits of code for you. It's like having basic
documentation inline in the editor, which saves you from having to look up type information in a separate
help window. IntelliSense features vary by language. For more information, see Visual C# IntelliSense,
Visual C++ Intellisense, JavaScript IntelliSense, and Visual Basic-Specific IntelliSense. The following
illustration shows some IntelliSense features at work:
Squiggles are wavy red underlines that alert you to errors or potential problems in your code in real time
as you type. This enables you to fix them immediately without waiting for the error to be discovered during
compilation or run time. If you hover over the squiggle, you see additional information about the error. A
light bulb may also appear in the left margin with suggestions for how to fix the error. For more
information, see Perform quick actions with light bulbs.
The Call Hierarchy window can be opened on the text editor context menu to show the methods that call,
and are called by, the method under the caret (insertion point).
CodeLens enables you to find references and changes to your code, linked bugs, work items, code reviews,
and unit tests, all without leaving the editor.
The Peek to Definition window shows a method or type definition inline, without navigating away from
your current context.
The Go To Definition context menu option takes you directly to the place where the function or object is
defined. Other navigation commands are also available by right-clicking in the editor.
A related tool, the Object Browser, enables you to inspect .NET or Windows Runtime assemblies on your
system to see what types they contain and what members (properties, methods, events, etc.) those types
contain.
Manage your source code and collaborate with others
You can manage your source code in Git repos hosted by any provider, including GitHub. Or use Visual Studio
Team Services (VSTS) to manage code alongside bugs and work items for your whole project. See Get Started with
Git and Team Services to learn more about managing Git repos in Visual Studio using Team Explorer. Visual Studio
also has other built-in source control features. To learn more about them, see New Git Features in Visual Studio
2017 (blog).
Visual Studio Team Services is a cloud-based service for hosting software projects and enabling collaboration in
teams. VSTS supports both Git and Team Foundation Source Control systems, as well as Scrum, CMMI and Agile
development methodologies. Team Foundation Version Control (TFVC) uses a single, centralized server repository
to track and version files. Local changes are always checked in to the central server where other developers can get
the latest changes.
Team Foundation Server (TFS) is the application lifecycle management hub for Visual Studio. It enables everyone
involved with the development process to participate using a single solution. TFS is useful for managing
heterogeneous teams and projects, too.
If you have a Visual Studio Team Services account or a Team Foundation Server on your network, you connect to it
through the Team Explorer window in Visual Studio. From this window you can check code into or out of source
control, manage work items, start builds, and access team rooms and workspaces. You can open Team Explorer
from the Quick Launch box, or on the main menu from View, Team Explorer or from Team, Manage
Connections.
The following image shows the Team Explorer window for a solution that is hosted in VSTS.
For more information about Visual Studio Team Services, see Visual Studio Team Services. For more information
about Team Foundation Server, see Team Foundation Server.
Server Explorer helps you browse and manage SQL Server instances and assets locally, remotely, and on Azure,
Salesforce.com, Office 365, and websites. To open Server Explorer, on the main menu, choose View, Server
Explorer. See Add new connections for more information on using Server Explorer.
SQL Server Data Tools (SSDT) is a powerful development environment for SQL Server, Azure SQL Database and
Azure SQL Data Warehouse. It enables you to build, debug, maintain, and refactor databases. You can work with a
database project, or directly with a connected database instance on- or off-premises.
SQL Server Object Explorer in Visual Studio provides a view of your database objects similar to SQL Server
Management Studio. SQL Server Object Explorer enables you to do light-duty database administration and design
work, including editing table data, comparing schemas, executing queries by using contextual menus right from
SQL Server Object Explorer, and more.
Extend Visual Studio
If Visual Studio doesn't have the exact functionality you need, you can add it! You can personalize the IDE based on
your workflow and style, add support for external tools not yet integrated with Visual Studio, and modify existing
functionality to increase your productivity. Visual Studio provides tools, controls, and templates from Microsoft,
our partners, and the community. To learn more about extending Visual Studio, see Extend Visual Studio IDE.
See also
Visual Studio IDE
Visual Studio Downloads
The Visual Studio Blog
Visual Studio Forums
Microsoft Virtual Academy
Channel 9
Personalize the Visual Studio IDE
10/18/2017 • 1 min to read • Edit Online
You can personalize Visual Studio in various ways to best support your own development style and
requirements. This topic briefly describes different personalizations and where to find more information.
Additional options are also exposed through the Environment Options Dialog Box. Furthermore, many of your
settings roam with you across Visual Studio instances. See Synchronized Settings.
Window layouts
You can define and save multiple window layouts and switch between them. For example, you can define a layout
for coding and one for debugging. To arrange window positions and behavior, and save custom layouts, see
Customizing window layouts.
External tools
To customize which external tools appear in menus and toolbars, see Managing External Tools.
Start page
To create a custom start page for you and your team, see Customizing the Start Page.
See Also
Visual Studio IDE
How to: Change Fonts and Colors in Visual Studio
10/18/2017 • 1 min to read • Edit Online
You can customize the color of the IDE frame and tool windows in Visual Studio in several ways.
TIP
For information about how to change the colors of the code editor, see How to: Change Fonts and Colors in the Editor.
IMPORTANT
When you change a color theme, text in the IDE reverts to the default or previously customized fonts and sizes.
If you have Visual Studio Professional, Visual Studio Premium, or Visual Studio Ultimate, you can install additional
predefined color themes and create your own by downloading and installing the Visual Studio 2013 Color Theme
Editor.
WARNING
This option sets high contrast for all applications and UI on the current computer.
TIP
If you want to change the font for tool windows only, in the Show settings for list, choose [All Text Tool
Windows].
You can customize Visual Studio not only by adding and removing toolbars and menus on the menu bar but also
by adding and removing commands on any given toolbar or menu.
WARNING
After you customize a toolbar or menu, make sure that its check box remains selected in the Customize dialog box.
Otherwise, your changes won't persist after you close and reopen Visual Studio.
In this topic:
Adding, removing, or moving a menu on the menu bar
Adding, removing, or moving a toolbar
Customizing a menu or a toolbar
Resetting a menu or a toolbar
To remove a custom toolbar, choose it in the Toolbars list, and then choose the Delete button.
IMPORTANT
You can delete toolbars that you create but not default toolbars.
To move a toolbar to a different docking location, choose it in the Toolbars list, choose the Modify
Selection button, and then choose a location in the list that appears.
You can also drag a toolbar by its left edge to move it anywhere in the main docking area.
NOTE
For more information about how to improve the usability and accessibility of toolbars, see How to: Set IDE
Accessibility Options.
To delete a command, choose it in the Controls list, and then choose the Delete button.
To reorder commands, choose a command in the Controls list, and then choose the Move Up or
Move Down button.
To separate commands into groups, choose a command in the Controls list, choose the Modify
Selection button, and then choose Begin a Group in the menu that appears.
In Visual Studio you can customize the position, size and behavior of windows to create window layouts that work
best for various development workflows. When you customize the layout, the IDE remembers it. For example, if
you change the docking location of Solution Explorer and then close Visual Studio, the next time that you start,
even if you are working on another computer, Solution Explorer will be docked in that same location. You can
also give a custom layout a name and save it, and then switch between layouts with a single command. For
example you could create a layout for editing, and another for debugging, and switch between them by using the
Window | Apply Window Layout menu command.
Kinds of windows
Tool and document windows
The IDE has two basic window types, tool windows and document windows. Tool windows include Solution
Explorer, Server Explorer, Output Window, Error List, the designers, the debugger windows, and so on. Document
windows contain source code files, arbitrary text files, config files, and so on. Tool windows can be resized and
dragged by their title bar. Document windows can be dragged by their tab. Right-click on the tab or title bar to set
other options on the window.
The Window menu shows options for docking, floating and hiding windows in the IDE. Right click on a window
tab or title bar to see additional options for that specific window. You can display more than one instance of
certain tool windows at a time. For example, you can display more than one web browser window, and you can
create additional instances of some tool windows by choosing New Window on the Window menu.
Preview tab (document windows)
In the Preview tab, you can view files in the editor without opening them. You can preview files by choosing them
in Solution Explorer, during debugging when you step into files, with Go to Definition, and when you browse
through results of a search. Preview files appear in a tab on the right side of the document tab well. The file opens
for editing if you modify it or choose the Open.
Tab groups
Tab Groups extend your ability to manage limited workspace while you are working with two or more open
documents in the IDE. You can organize multiple document windows and tool windows into either vertical or
horizontal Tab Groups and shuffle documents from one Tab Group to another.
Split windows
When you have to view or edit two locations at once in a document, you can split windows. To divide your
document into two independently scrolling sections, click Split on the Window menu. Click Remove Split on the
Window menu to restore the single view.
Toolbars
Toolbars can be arranged by dragging, or by using the Customize dialog box. For more information about how to
position and customize toolbars, see How to: Customize Menus and Toolbars.
NOTE
Your computer might show different names or locations for some of the Visual Studio user interface elements in the
following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For
more information, see Personalize the Visual Studio IDE.
Dock Windows
When you click and drag the title bar of a tool window, or the tab of document window, a guide diamond appears.
During the drag operation, when the mouse cursor is over one of the arrows in the diamond, a shaded area will
appear that shows you where the window will be docked if you release the mouse button now.
To move a dockable window without snapping it into place, choose the Ctrl key while you drag the window.
To return a tool window or document window to its most recent docked location, press CTRL while you double-
click the title bar or tab of the window.
The following illustration shows the guide diamond for document windows, which can only be docked within the
editing frame:
Tool windows can be fastened to one side of a frame in the IDE or within the editing frame. A guide diamond
appears when you drag a tool window to another location to help you to easily re-dock the window.
Guide diamond for tool windows
The following illustration shows Solution Explorer being docked in a new location, which is shown by the blue
shaded area:
NOTE
To set whether Auto Hide operates on tool windows individually or as docked groups, select or clear Auto Hide button
affects active tool windows only in the Options dialog box. For more information, see General, Environment, Options
Dialog Box.
NOTE
Tool windows that have Auto Hide enabled may temporarily slide into view when the window has focus. To hide the window
again, select an item outside of the current window. When the window loses focus, it slides back out of view.
TIP
You can create multiple instances of Solution Explorer and move them to another monitor. Right-click the window and
choose New Solution Explorer View. You can return all windows back to the original monitor by double-clicking while
choosing the Ctrl key.
1. In the New Project dialog, create a Visual C# WPF Desktop Application and call it whatever you like.
Pretend that this is the project where we'll be working on the user interface, so we want to maximize the
space for the designer window and move other tool windows out of the way.
2. If you have multiple monitors, pull the Solution Explorer window and the Properties window over to
your second monitor. On a single monitor system, try closing all the windows except the designer.
3. Press Ctrl + Alt + X to display the Toolbox. If the window is docked, drag it so that it floats somewhere
where you'd like to position it, on either monitor.
4. Press F5 to put Visual Studio into debugging mode. Adjust the position of the Autos, Call Stack and Output
debugging windows the way you want them. The layout you are about to create will apply to both editing
mode and debugging mode.
5. When your layouts in both debugging mode and editing mode are how you want them, from the main
menu choose Window > Save Window Layout. Call this layout "Designer."
Note that your new layout is assigned the next Keyboard shortcut from the reserved list of Ctrl + Alt + 1...0.
C r e a t e a d a t a b a se p r o j e c t a n d l a y o u t
1. To switch between layouts, use the Keyboard shortcuts, or from the main menu choose Window > Apply
Window Layout.
After applying the UI layout, note how the layout is preserved both in editing mode and in debug mode.
If you have a multi monitor setup at work and a single monitor laptop at home, you can create layouts that
are optimized for each machine.
Note: If you apply a multi-monitor layout on a single-monitor system, the floating windows that you placed
on the second monitor will now be hidden behind the Visual Studio window. You can bring these windows
to the front by pressing Alt + Tab. If you later open Visual Studio with multiple monitors, you can restore
the windows to their specified positions by re-applying the layout.
Man age an d roam you r layou t s
1. You can remove, rename or reorder your custom layout by choosing Window > Manage Window
Layouts. If you move a layout, the key binding is automatically adjusted to reflect the new position in the
list. The bindings cannot be otherwise modified, and so you can store a maximum of 10 layouts at a time.
To remind yourself which keyboard shortcut is assigned to which layout, choose Window > Apply
Window Layout.
These layouts automatically roam between Visual Studio editions, and also between Blend instances on
separate machines, and from any Express edition to any other Express organization. However, layouts do
not roam across Visual Studio, Blend and Express.
Related Topics
How to: Move Around in the IDE
Customize the start page for Visual Studio
10/18/2017 • 1 min to read • Edit Online
You can customize the start page for Visual Studio in several default ways, such as showing the Open Project
dialog box or opening the solution that was loaded most recently. You can also show a custom start page, which is
a Windows Presentation Foundation (WPF) XAML page that runs in a tool window and can run commands that are
internal to Visual Studio.
NOTE
If an error in a custom start page causes Visual Studio to crash, you can start Visual Studio in safe mode and then set it to
use the default start page. See /SafeMode (devenv.exe).
See also
Personalize the Visual Studio IDE
Manage external tools
10/18/2017 • 2 min to read • Edit Online
You can call external tools from inside Visual Studio by using the Tools menu. A few default tools are available
from the Tools menu, but you can add other executables of your own.
The following is a full list of arguments that can be used when defining an external tool.
NOTE
The IDE status bar displays the Current Line and Current Column variables to indicate where the insertion point is located in
the active Code Editor. The Current Text variable returns the text or code selected at that location.
Item File Name $(ItemFilename) The file name of the current file (file
name).
Project file name $(ProjFileName) The file name of the current project
(drive + path + file name).
Solution file name $(SolutionFileName) The file name of the current solution
(drive + path + file name).
See also
C/C++ Build Tools
Synchronize your settings in Visual Studio
10/18/2017 • 2 min to read • Edit Online
When you sign in to Visual Studio on multiple computers using the same personalization account, by default your
settings are synchronized on all computers.
Synchronized settings
By default, the following settings are synchronized.
Development settings (You have to select a set of settings the first time you run Visual Studio, but you can
change the selection anytime. For more information, see Personalize the Visual Studio IDE.)
The following options in the Tools | Options pages:
Theme and menu bar casing settings, on the Environment, General options page
All settings on the Environment, Fonts and Colors options page
All keyboard shortcuts, on the Environment, Keyboard options page
All settings on the Environment, Tabs and Windows options page
All settings on the Environment, StartUp options page
All settings on the Text Editor options pages
All settings on the XAML Designer options pages
User-defined command aliases. For more information about how to define command aliases, see Visual
Studio Command Aliases.
User-defined window layouts in Window | Manage Window Layouts page
See also
Personalizing the IDE
Get Started Developing with Visual Studio
10/18/2017 • 2 min to read • Edit Online
Welcome to Visual Studio! After you have downloaded the product, these pages will help you get started coding.
Make web apps: Tools to create and deploy modern web applications.
Do a tutorial | Browse the docs | Watch a video
Make cross-platform mobile apps in HTML/Javascript (Apache Cordova) : Apache Cordova is an
open-source cross-platform environment that is based on HTML/CSS/Javascript. Your Javascript code
executes in a wrapper that targets a specific platform and enables access to all the hardware capabilities of
the device. Develop apps for the Apple Store, the Android store, and the Windows Store.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make cross-platform mobile apps in C# or Visual Basic (Xamarin) : Get started using Visual Studio and
Tools for Xamarin to create mobile apps that run on Android, iOS, and the Universal Windows Platform
from a shared code base.
Load a sample: Tasky Portable (native UI) or Xamarin Forms Todo sample (Xamarin.Forms shared UI) | Do a
tutorial | Browse the docs | Watch a video
Make native cross-platform apps and libraries in C++ Go here to get started creating C++ apps and
libraries that run on Android, iOS, and the Universal Windows Platform.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make games with DirectX : Get started creating Universal Windows Platform games using DirectX.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make games with Unity : Get started creating cross-platform games using Unity framework.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make Universal Windows Platform apps : Get started creating apps that run on the Universal Windows
Platform (XBox, PCs, tablets, Windows Phone, Surface Hub, and Internet of Things).
Load a sample | Do a tutorial | Browse the docs | Watch a video
Make desktop applications : Go here to get started creating traditional desktop applications that run on
Windows PCs.
Load a sample | Do a tutorial | Browse the docs
Make Office applications : Get started creating Office applications that extend and customize Word, Excel,
Outlook and Powerpoint with Office 365 services.
Load a sample | Do a tutorial | Browse the docs | Watch a video
Tour Visual Studio Team Services and Team Foundation Server Learn more about Visual Studio Team
Services and Team Foundation Server.
In this section
Getting Started with Visual C# and Visual Basic Writing JavaScript Code
Visual C++ for Cross-Platform Mobile Development Introduction to Functional Programming with F#
Getting Started with C++ Getting Started with Debugging in Visual Studio
Getting Started with Visual C# and Visual Basic using
Visual Studio
10/18/2017 • 1 min to read • Edit Online
Whether you are new to Visual C# or Microsoft Visual Basic, this is the place to start. Getting Started Help is a
series of sequential lessons that introduces you to Visual C# and Visual Basic. Have fun, and write some great
software.
To learn about Visual C++, see Visual C++ resources.
In This Section
Walkthrough: Create a Simple Application
Identify the basic windows in the Visual Studio IDE, optimize your development experience by configuring a
setting, and then build a simple program.
Tutorial 1: Create a Picture Viewer
Build a program that loads a picture from a file and displays it in a window. Learn how to drag controls like buttons
and picture boxes on your form, set their properties, and use containers to smoothly resize the form. Get started
writing code.
Tutorial 2: Create a Timed Math Quiz
Build a timed math quiz game, where the player must answer four random arithmetic problems within a specified
time. Learn how to generate random numbers using the Random class, trigger events using a Timer control,
control program flow using if else statements, and perform basic arithmetic operations.
Tutorial 3: Create a Matching Game
Build a matching game, where the player must match pairs of hidden icons. Learn how to hold objects using a
List object, use a foreach loop, keep track of a form's state using reference variables, build an event handler that
you can use with multiple objects, and make a timer fire exactly once when started.
See also
Get started developing with Visual Studio
Quickstart: use Visual Studio to create your first
ASP.NET Core web app
10/19/2017 • 2 min to read • Edit Online
In this 5-10 minute introduction to the Visual Studio integrated development environment (IDE), you'll create a
simple C# ASP.NET Core web application. If you haven't already installed Visual Studio, install it for free here.
Create a project
First, you'll create an ASP.NET Core web application project. The project type comes with template files that
constitute a functional web application, before you've even added anything!
1. Open Visual Studio 2017.
2. From the top menu bar, choose File, New, Project....
3. In the New Project dialog box, in the left pane, expand Visual C#, then choose .NET Core. In the middle
pane, choose ASP.NET Core Web Application, then choose OK.
If you don't see the .NET Core project template, cancel out of the New Project dialog box and from the top
menu bar, choose Tools, Get Tools and Features.... The Visual Studio Installer launches. Choose the
ASP.NET and web development workload, then choose Modify.
4. In the New ASP.NET Core Web Application dialog box, select ASP.NET Core 2.0 from the top drop-down
menu. (If you don't see ASP.NET Core 2.0 in the list, install it by following the Download link that should
appear in a yellow bar near the top of the dialog box.) Choose OK.
Explore the IDE
1. In the Solution Explorer toolbar, expand the Pages folder, then choose About.cshtml to open it in the
editor. This file corresponds to a page called About in the web application.
2. In the editor, choose AboutModel and then press F12 or choose Go To Definition from the context (right-
click) menu. This command takes you to the definition of the AboutModel C# class.
3. Next we'll clean up the using directives at the top of the file using a simple shortcut. Choose any of the
greyed-out using directives and a Quick Actions light bulb will appear just below the caret or in the left
margin. Choose the light bulb, and then choose Remove Unnecessary Usings.
The unnecessary usings are deleted from the file.
4. In the OnGet() method, change the body to the following code:
5. You'll see two wavy underlines appear under Environment and String, because these types are not in
scope. Open the Error List toolbar to see the same errors listed there. (If you don't see the Error List toolbar,
choose View, Error List from the top menu bar.)
6. In the editor window, place your cursor on either line that contains the error, then choose the Quick Actions
light bulb in the left margin. From the drop-down menu, choose using System; to add this directive to the
top of your file and resolve the errors.
See also
Getting Started with C# and Visual Basic using Visual Studio Getting started with Razor Pages in ASP.NET Core
Walkthrough: Create a Simple Application with Visual
C# or Visual Basic
10/18/2017 • 8 min to read • Edit Online
By completing this walkthrough, you'll become familiar with many of the tools, dialog boxes, and designers that
you can use when you develop applications with Visual Studio. You'll create a simple "Hello, World" application,
design the UI, add code, and debug errors, while you learn about working in the integrated development
environment (IDE).
This topic contains the following sections:
Configure the IDE
Create a simple application
Debug and test the application
After Visual Studio launches, you'll see tool windows, the menus and toolbars, and the main window space. Tool
windows are docked on the left and right sides of the application window, with Quick Launch, the menu bar, and
the standard toolbar at the top. In the center of the application window is the Start Page. When you load a
solution or project, editors and designers appear in the space where the Start Page is. When you develop an
application, you'll spend most of your time in this central area.
2. Choose the Visual Basic or the Visual C# WPF App template by choosing in the left pane Installed, Visual
C#, Windows Classic Desktop, for example, and then choosing WPF App (.NET Framework) in the
middle pane. Name the project HelloWPFApp at the bottom of the New Project dialog.
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. (For more information, see WPF Designer for Windows Forms Developers.) The following items
appear in Solution Explorer:
After you create the project, you can customize it. By using the Properties window (found on the View
menu), you can display and change options for project items, controls, and other items in an application.
To change the name of MainWindow.xaml
Let's give MainWindow a more specific name.
1. In Solution Explorer, select MainWindow.xaml. You should see the Properties window, but if you don't,
choose the View menu and then the Properties Window item.
2. Change the File Name property to Greetings.xaml .
Solution Explorer shows that the name of the file is now Greetings.xaml, and the nested code file is now
named Greetings.xaml.vb or Greetings.xaml.cs. This code file is nested under the .xaml file node to show
they are closely related to each other.
Design the user interface (UI )
We will add three types of controls to this application: a TextBlock control, two RadioButton controls, and a Button
control.
To add a TextBlock control
1. Open the Toolbox window by choosing the View menu and the Toolbox item.
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.
Your window should resemble the following illustration:
2. Re-center the TextBlock if necessary, and save your changes by pressing Ctrl-s or using the File menu item.
Next, you'll add two RadioButton controls to the form.
To add radio buttons
1. In the Toolbox, find the RadioButton control.
2. Add two RadioButton controls to the design surface by choosing the RadioButton item and dragging it to
the window on the design surface. Move the buttons (by selecting them and using the arrow keys) so that
the buttons appear side by side under the TextBlock control.
Your window should look like this:
3. In the Properties window for the left RadioButton control, change the Name property (the property at the
top of the Properties window) to HelloButton.
4. In the Properties window for the right RadioButton control, change the Name property to
GoodbyeButton, and then save your changes.
You can now add display text for each RadioButton control. The following procedure updates the Content
property for a RadioButton control.
To add display text for each radio button
1. On the design surface, open the shortcut menu for HelloButton by pressing the right mouse button on
HelloButton, choose Edit Text, and then enter 'Hello'.
2. Open the shortcut menu for GoodbyeButton by pressing the right mouse button on GoodbyeButton, choose
Edit Text, and then enter 'Goodbye'.
To set a radio button to be checked by default
In this step we'll set HelloButton to be checked by default so that one of the two radio buttons is always selected.
In the XAML view, locate the markup for HelloButton and add an IsChecked attribute:
IsChecked="True"
End Sub
if (HelloButton.IsChecked == true)
{
MessageBox.Show("Hello.");
}
else if (GoodbyeButton.IsChecked == true)
{
MessageBox.Show("Goodbye.");
}
A Break Mode window appears, and the Output window indicates that an IOException has occurred:
Cannot locate resource 'mainwindow.xaml'.
2. Stop the debugger by choosing Debug, Stop Debugging.
We renamed MainWindow.xaml to Greetings.xaml at the start of this walkthrough, but the code still refers
to mainwindow.xaml as the startup URI for the application, so the project can't start.
To specify Greetings.xaml as the startup URI
1. In Solution Explorer, open the App.xaml file (in the C# project) or the Application.xaml file (in the Visual
Basic project).
2. Change StartupUri="MainWindow.xaml" to StartupUri="Greetings.xaml" , and then save the changes.
Start the debugger again (press F5). You should see the Greetings window of the application. Now close the
application window to stop debugging.
To debug with breakpoints
You can test the code during debugging by adding some breakpoints. You can add breakpoints by choosing
Debug, Toggle Breakpoint, by clicking in the left margin of the editor next to the line of code where you want
the break to occur, or by pressing F9.
To add breakpoints
1. Open Greetings.xaml.vb or Greetings.xaml.cs, and select the following line: MessageBox.Show("Hello.")
2. Add a breakpoint from the menu by selecting Debug, then Toggle Breakpoint.
A red circle appears next to the line of code in the far left margin of the editor window.
3. Select the following line: MessageBox.Show("Goodbye.") .
4. Press the F9 key to add a breakpoint, and then press F5 to start debugging.
5. In the Greetings window, choose the Hello radio button, and then choose the Display button.
The line MessageBox.Show("Hello.") is highlighted in yellow. At the bottom of the IDE, the Autos, Locals, and
Watch windows are docked together on the left side, and the Call Stack, Breakpoints, Command, Immediate,
and Output windows are docked together on the right side.
6. On the menu bar, choose Debug, Step Out.
The application resumes execution, and a message box with the word "Hello" appears.
7. Choose the OK button on the message box to close it.
8. In the Greetings window, choose the Goodbye radio button, and then choose the Display button.
The line MessageBox.Show("Goodbye.") is highlighted in yellow.
9. Choose the F5 key to continue debugging. When the message box appears, choose the OK button on the
message box to close it.
10. Close the application window to stop debugging.
11. On the menu bar, choose Debug, Disable All Breakpoints.
Build a release version of the application
Now that you've verified that everything works, you can prepare a release build of the application.
To clean the solution files and build a release version
1. On the main menu, select Build, Clean solution to delete intermediate files and output files that were
created during previous builds. This is not necessary, but it cleans up the debug build outputs.
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 walkthrough! You can find the .exe you built under your solution and project
directory (...\HelloWPFApp\HelloWPFApp\bin\Release\). If you want to explore more examples, see Visual Studio
Samples.
See Also
What's New in Visual Studio 2017
Get Started Developing with Visual Studio
Productivity Tips
Tutorial 1: Create a Picture Viewer
10/18/2017 • 2 min to read • Edit Online
In this tutorial, you build a program that loads a picture from a file and displays it in a window. You learn how to
drag controls like buttons and picture boxes on your form, set their properties, and use containers to smoothly
resize the form. You also get started writing code. You learn how to:
Create a new project.
Test (debug) an application.
Add basic controls like check boxes and buttons to a form.
Position controls on a form using layouts.
Add Open File and Color dialog boxes to a form.
Write code using IntelliSense and code snippets.
Write event handler methods.
When you finish, your program will look like the following picture.
NOTE
These videos use an earlier version of Visual Studio, so there are slight differences in some menu commands and other user
interface elements. However, the concepts and procedures work similarly in the current version of Visual Studio. Visual C#
and Visual Basic are both covered in this tutorial, so focus on information specific to the programming language that you're
using.
To see code for Visual Basic, choose the VB tab at the top of code blocks, and to see code for Visual C#, choose the C# tab. If
you're interested in learning about Visual C++, see Getting Started and C++ Language Tutorial.
If you're interested in learning how to write Visual C# or Visual Basic apps for the Windows Store, see Create your first
Windows Store app using C# or Visual Basic. For information about creating JavaScript apps for the Windows Store, see
Create your first Windows Store app using JavaScript.
Related Topics
TITLE DESCRIPTION
Step 1: Create a Windows Forms Application Project Begin by creating a Windows Forms application project.
Step 2: Run Your Program Run the Windows Forms application program that you created
in the previous step.
Step 3: Set Your Form Properties Change the way your form looks using the Properties
window.
Step 4: Lay Out Your Form with a TableLayoutPanel Control Add a TableLayoutPanel control to your form.
Step 5: Add Controls to Your Form Add controls, such as a PictureBox control and a
CheckBox control, to your form. Add buttons to your form.
Step 6: Name Your Button Controls Rename your buttons to something more meaningful.
Step 7: Add Dialog Components to Your Form Add an OpenFileDialog component and a ColorDialog
component to your form.
Step 8: Write Code for the Show a Picture Button Event Write code using the IntelliSense tool.
Handler
Step 9: Review, Comment, and Test Your Code Review and test your code. Add comments as needed.
Step 10: Write Code for Additional Buttons and a Check Box Write code to make other buttons and a check box work using
IntelliSense.
Step 11: Run Your Program and Try Other Features Run your program and set the background color. Try other
features, such as changing colors, fonts, and borders.
Step 1: Create a Windows Forms Application Project
10/18/2017 • 3 min to read • Edit Online
When you create a picture viewer, the first step is to create a Windows Forms Application project.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To create a Windows Forms Application project
1. On the menu bar, choose File, New, Project. The dialog box should look like this.
NOTE
Your window layout may not look exactly like this illustration. The precise window layout depends on the version of
Visual Studio, the programming language you are using, and other factors. However, you should verify that all three
windows appear.
IDE window
The interface contains three windows: a main window, Solution Explorer, and the Properties window.
If any of these windows are missing, restore the default window layout by, on the menu bar, choosing
Window, Reset Window Layout. You can also display windows by using menu commands. On the menu
bar, choose View, Properties Window or Solution Explorer. If any other windows are open, close them
by choosing the Close (x) button in their upper-right corners.
5. The illustration shows the following windows (going clockwise from the upper-left corner):
Main window In this window, you'll do most of your work, such as working with forms and editing
code. In the illustration, the window shows a form in the Form Editor. At the top of the window, the
Start Page tab and the Form1.cs [Design] tab appear. (In Visual Basic, the tab name ends with .vb
instead of .cs.)
Solution Explorer window In this window, you can view and navigate to all items in your solution. If
you choose a file, the contents of the Properties window changes. If you open a code file (which ends
in .cs in Visual C# and .vb in Visual Basic), the code file or a designer for the code file appears. A
designer is a visual surface onto which you can add controls such as buttons and lists. For Visual
Studio forms, the designer is called the Windows Forms Designer.
Properties window In this window, you can change the properties of items that you choose in the
other windows. For example, if you choose Form1, you can change its title by setting the Text
property, and you can change the background color by setting the Backcolor property.
NOTE
The top line in Solution Explorer shows Solution 'PictureViewer' (1 project), which means that Visual Studio
created a solution for you. A solution can contain more than one project, but for now, you'll work with solutions that
contain only one project.
When you created a new solution, you actually built a program that runs. It doesn't do much yet—it just displays
an empty window that shows Form1 in the title bar. But it does run, as you're about to find out.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To run your program
1. Use one of the following methods to run your program.
Choose the F5 key.
On the menu bar, choose Debug, Start Debugging.
On the toolbar, choose the Start Debugging button, which appears as follows.
Debugging toolbar
4. Use one of the following methods to stop your program.
On the toolbar, choose the Stop Debugging button.
On the menu bar, choose Debug, Stop Debugging.
Choose the X button in the upper corner of the Form1 window.
NOTE
When you run your program from inside the IDE, it's called debugging because you typically do it to locate and fix
bugs (errors) in the program. Although this program is small and doesn't really do anything yet, it's still a real
program. You follow the same procedure to run and debug other programs. To learn more about debugging, see
Debugger Basics.
To continue or review
To go to the next tutorial step, see Step 3: Set Your Form Properties.
To return to the previous tutorial step, see Step 1: Create a Windows Forms Application Project.
Step 3: Set Your Form Properties
10/18/2017 • 2 min to read • Edit Online
Next, you use the Properties window to change the way your form looks.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 1 or Tutorial 1:
Create a Picture Viewer in C# - Video 1. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To set your form properties
1. Be sure you're looking at Windows Forms Designer. In the Visual Studio integrated development
environment (IDE), choose the Form1.cs [Design] tab (or the Form1.vb [Design] tab in Visual Basic).
2. Choose anywhere inside the form Form1 to select it. Look at the Properties window, which should now be
showing the properties for the form. Forms have various properties. For example, you can set the
foreground and background color, title text that appears at the top of the form, size of the form, and other
properties.
NOTE
If the Properties window doesn't appear, stop your program by choosing the square Stop Debugging button on
the toolbar, or just close the window. If the program is stopped and you still don't see the Properties window, on
the menu bar, choose View, Properties Window.
3. After the form is selected, find the Text property in the Properties window. Depending on how the list is
sorted, you might need to scroll down. Choose Text, type Picture Viewer, and then choose ENTER. Your
form should now have the text Picture Viewer in its title bar, and the Properties window should look
similar to the following picture.
Properties window
NOTE
Properties can be ordered by a Categorized or Alphabetical view. You can switch between these two views by using
the buttons on the Properties window. In this tutorial, it's easier to find properties through the Alphabetical view.
4. Go back to Windows Forms Designer. Choose the form's lower-right drag handle, which is the small white
square in the lower-right of the form and appears as follows.
Drag handle
Drag the handle to resize the form so the form is wider and a bit taller.
5. Look at the Properties window, and notice that the Size property has changed. The Size property changes
each time you resize the form. Try dragging the form's handle to resize it to a form size of approximately
550, 350 (no need to be exact), which should work well for this project. As an alternative, you can enter the
values directly in the Size property and then choose the ENTER key.
6. Run your program again. Remember, you can use any of the following methods to run your program.
Choose the F5 key.
On the menu bar, choose Debug, Start Debugging.
On the toolbar, choose the Start Debugging button, which appears as follows.
In this step, you add a TableLayoutPanel control to your form. The TableLayoutPanel helps properly align controls
in the form that you will add later.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 2 or Tutorial 1:
Create a Picture Viewer in C# - Video 2. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To lay out your form with a TableLayoutPanel control
1. On the left side of the Visual Studio IDE, locate the Toolbox tab. Choose the Toolbox tab, and the Toolbox
appears. (Or, on the menu bar, choose View, Toolbox.)
2. Choose the small triangle symbol next to the Containers group to open it, as shown in the following
picture.
Containers group
3. You can add controls like buttons, check boxes, and labels to your form. Double-click the TableLayoutPanel
control in the Toolbox. (Or, you can drag the control from the toolbox onto the form.) When you do this, the
IDE adds a TableLayoutPanel control to your form, as shown in the following picture.
TableLayoutPanel control
NOTE
After you add your TableLayoutPanel, if a window appears inside your form with the title TableLayoutPanel Tasks,
choose anywhere inside the form to close it. You will learn more about this window later in the tutorial.
Notice how the Toolbox expands to cover your form when you choose its tab, and closes after you choose
anywhere outside of it. That's the IDE auto-hide feature. You can turn it on or off for any of the windows by
choosing the pushpin icon in the upper-right corner of the window to toggle auto-hide and lock it in place.
The pushpin icon appears as follows.
Pushpin icon
4. Be sure TableLayoutPanel is selected by choosing it. You can verify what control is selected by looking at
the drop-down list at the top of the Properties window, as shown in the following picture.
NOTE
A TableLayoutPanel works like a table in Microsoft Office Word: It has rows and columns, and an individual cell can
span multiple rows and columns. Each cell can hold one control (like a button, a check box, or a label). Your
TableLayoutPanel will have a PictureBox control spanning its entire top row, a CheckBox control in its lower-left
cell, and four Button controls in its lower-right cell.
8. Currently, the TableLayoutPanel has two equal-size rows and two equal-size columns. You need to resize
them so the top row and right column are both much bigger. In Windows Forms Designer, select the
TableLayoutPanel. In the upper-right corner, there is a small black triangle button, which appears as follows.
Triangle button
This button indicates that the control has tasks that help you set its properties automatically.
9. Choose the triangle to display the control's task list, as shown in the following picture.
TableLayoutPanel tasks
10. Choose the Edit Rows and Columns task to display the Column and Row Styles window. Choose
Column1, and set its size to 15 percent by being sure the Percent button is selected and entering 15 in
the Percent box. (That's a NumericUpDown control, which you will use in a later tutorial.) Choose Column2
and set it to 85 percent. Don't choose the OK button yet, because the window will close. (But if you do, you
can reopen it using the task list.)
In this step, you add controls, such as a PictureBox control and a CheckBox control, to your form. You then add
buttons to your form.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 2 or Tutorial 1:
Create a Picture Viewer in C# - Video 2. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To add controls to your form
1. Go to the Toolbox tab (located on the left side of the Visual Studio IDE) and expand the Common Controls
group. This shows the most common controls that you see on forms.
2. Choose the TableLayoutPanel control on the form. To verify that the TableLayoutPanel is selected, make sure
that its name appears in the dropdown list box at the top of the Properties window. You can also choose
form controls by using the dropdown list box at the top of the Properties window. Choosing a control this
way can often be easier than choosing a tiny control with a mouse.
3. Double-click the PictureBox item to add a PictureBox control to your form. Because the TableLayoutPanel is
docked to fill your form, the IDE adds the PictureBox control to the first empty cell (the upper left corner).
4. Choose the new PictureBox control to select it, and then choose the black triangle on the new PictureBox
control to display its task list, as shown in the following picture.
PictureBox tasks
NOTE
If you accidentally add the wrong type of control to your TableLayoutPanel, you can delete it. Right-click the control,
and then choose Delete on its context menu. You can also remove controls from the form by using the menu bar.
On the menu bar, choose Edit, Undo, or Edit, Delete.
5. Choose the Dock in parent container link. This automatically sets the PictureBox Dock property to Fill. To
see this, choose the PictureBox control to select it, go to the Properties window, and be sure that the Dock
property is set to Fill.
6. Make the PictureBox span both columns by changing its ColumnSpan property. Choose the PictureBox
control and set its ColumnSpan property to 2. Also, when the PictureBox is empty, you want to show an
empty frame. Set its BorderStyle property to Fixed3D.
NOTE
If you don't see a ColumnSpan property for your PictureBox, then it's likely that the PictureBox was added to the
form rather than the TableLayoutPanel. To fix this, choose the PictureBox, delete it, choose the TableLayoutPanel, and
then add a new PictureBox.
7. Choose the TableLayoutPanel on the form and then add a CheckBox control to the form. Double-click the
CheckBox item in the Toolbox to add a new CheckBox control to the next free cell in your table. Because a
PictureBox takes up the first two cells in the TableLayoutPanel, the CheckBox control is added to the lower-
left cell. Choose the Text property and type in the word Stretch, as shown in the following picture.
NOTE
A FlowLayoutPanel is a container that arranges other controls in neat rows in order. When you resize a
FlowLayoutPanel, if it has room to lay out all of its controls in a single row, it does that. Otherwise, it arranges them
in lines, one on top of the other. You will use a FlowLayoutPanel to hold four buttons. If the buttons arrange one on
top another when added, be sure that the FlowLayoutPanel is selected before adding the buttons. Although it was
stated earlier that each cell can hold only one control, the lower-right cell of the TableLayoutPanel has four button
controls. This is because you can put a control in a cell that holds other controls. That kind of control is called a
container, and the FlowLayoutPanel is a container.
To add buttons
1. Choose the new FlowLayoutPanel that you added. Go to Common Controls in the Toolbox and double-
click the Button item to add a button control called button1 to your FlowLayoutPanel. Repeat to add
another button. The IDE determines that there's already a button called button1 and calls the next one
button2.
2. Typically, you add the other buttons using the Toolbox. This time, choose button2, and then on the menu
bar, choose Edit, Copy (or press Ctrl+C). On the menu bar, choose Edit, Paste (or press Ctrl+V) to paste a
copy of your button. Now paste it again. The IDE has now added button3 and button4 to the
FlowLayoutPanel.
NOTE
You can copy and paste any control. The IDE names and places the new controls in a logical manner. If you paste a
control into a container, the IDE chooses the next logical space for placement.
3. Choose the first button and set its Text property to Show a picture. Then set the Text properties of the
next three buttons to Clear the picture, Set the background color, and Close.
4. The next step is to size the buttons and arrange them so they align to the right side of the panel. Choose the
FlowLayoutPanel and look at its FlowDirection property. Change it so it's set to RightToLeft. As soon as
you do, 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.
NOTE
If the buttons are still in the wrong order, you can drag the buttons around the FlowLayoutPanel to rearrange them
in any order. You can choose a button and drag it left or right.
5. Choose the Close button to select it. Hold down the CTRL key and choose the other three buttons, so that
they are all selected. While all the buttons are selected, go to the Properties window and scroll up to the
AutoSize property. This property tells the button to automatically resize itself to fit all of its text. Set it to
true. Your buttons should now be sized properly and be in the right order. (As long as all four buttons are
selected, you can change all four AutoSize properties at the same time.) The following picture shows the
four buttons.
There's only one PictureBox on your form. When you added it, the IDE automatically named it pictureBox1.
There's only one CheckBox, which is named checkBox1. Soon, you will write some code, and that code will refer to
the CheckBox and PictureBox. Because there's only one of each of these controls, you will know what it means
when you see pictureBox1 or checkBox1 in your code.
NOTE
In Visual Basic, the default first letter of any control name is initial cap, so the names are PictureBox1, CheckBox1, and so
on.
There are four buttons on your form, and the IDE named them button1, button2, button3, and button4. By just
looking at their current names, you don't know which button is the Close button and which one is the Show a
picture button. That's why giving your button controls more informative names is helpful.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 3 or Tutorial 1:
Create a Picture Viewer in C# - Video 3. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To name your button controls
1. On the form, choose the Close button. (If you still have all the buttons selected, choose the ESC key to cancel
the selection.) Scroll in the Properties window until you see the (Name) property. (The (Name) property is
near the top when the properties are alphabetical.) Change the name to closeButton, as shown in the
following picture.
NOTE
If you try changing the name of your button to closeButton, with a space between the words close and Button, the
IDE displays an error message: "Property value is not valid." Spaces (and a few other characters) are not allowed in
control names.
2. Rename the other three buttons to backgroundButton, clearButton, and showButton. You can verify the
names by choosing the control selector drop-down list in the Properties window. The new button names
appear.
3. Double-click the Show a picture button on the form. As an alternative, choose the Show a picture button
on the form, and then choose the ENTER key. When you do, the IDE opens an additional tab in the main
window called Form1.cs (Form1.vb if you're using Visual Basic). This tab shows the code file behind the
form, as shown in the following picture.
End Sub
You are looking at code called showButton_Click() . The IDE added this to the form's code when you opened
the code file for the showButton button. At design-time, when you open the code file for a control in a
form, code is generated for the control if it doesn't already exist. This code, known as a method, runs when
you run your program and choose the control - in this case, the Show a picture button.
NOTE
In this tutorial, the Visual Basic code that's automatically generated has been simplified by removing everything
between the parentheses, (). Whenever this occurs, you can remove the same code. Your program will work either
way. For the remainder of the tutorials, any automatically generated code is simplified whenever possible.
5. Choose the Windows Forms Designer tab again (Form1.cs [Design] in Visual C#, Form1.vb [Design] in
Visual Basic) and then open the code file for the Clear the picture button to create a method for it in the
form's code. Repeat this for the remaining two buttons. Each time, the IDE adds a new method to the form's
code file.
6. To add one more method, open the code file for the CheckBox control in Windows Forms Designer to make
the IDE add a checkBox1_CheckedChanged() method. That method is called whenever the user selects or clears
the check box.
NOTE
When working on a program, you often move between the code editor and Windows Forms Designer. The IDE
makes it easy to navigate in your project. Use Solution Explorer to open Windows Forms Designer by double-
clicking Form1.cs in Visual C# or Form1.vb in Visual Basic, or on the menu bar, choose View, Designer.
The following shows the new code that you see in the code editor.
End Sub
End Sub
End Sub
End Sub
The five methods that you added are called event handlers, because your program calls them whenever an
event (like a user choosing a button or selecting a box) happens.
When you view the code for a control in the IDE at design time, Visual Studio adds an event handler method
for the control if one isn't there. For example, when you double-click a button, the IDE adds an event handler
for its Click event (which is called whenever the user chooses the button). When you double-click a check
box, the IDE adds an event handler for its CheckedChanged event (which is called whenever the user selects
or clears the box).
After you add an event handler for a control, you can return to it at any time from Windows Forms Designer
by double-clicking the control, or on the menu bar, choosing View, Code.
Names are important when you build programs, and 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
the showButton_Click() event handler method. Also, opening and closing parentheses () are usually added
after the method name to indicate that methods are being discussed. If you decide 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. See Rename Refactoring (C#) or Rename Refactoring (Visual Basic)
for more information.
To continue or review
To go to the next tutorial step, see Step 7: Add Dialog Components to Your Form.
To return to the previous tutorial step, see Step 5: Add Controls to Your Form.
Step 7: Add Dialog Components to Your Form
10/18/2017 • 2 min to read • Edit Online
To enable your program to open picture files and choose a background color, in this step, you add an
OpenFileDialog component and a ColorDialog component to your form.
A component is like a control in some ways. You use the Toolbox to add a component to your form, and you set its
properties using the Properties window. But unlike a control, adding a component to your form doesn't add a
visible item that the user can see on the form. Instead, it provides certain behaviors that you can trigger with code.
It's a component that opens an Open File dialog box.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 3 or Tutorial 1:
Create a Picture Viewer in C# - Video 3. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To add dialog components to your form
1. Choose the Windows Forms Designer (Form1.cs [Design] or Form1.vb [Design]) and then open the Dialogs
group in the Toolbox.
NOTE
The Dialogs group in the Toolbox has components that open many useful dialog boxes for you, which can be used
for opening and saving files, browsing folders, and choosing fonts and colors. You use two dialog components in this
project: OpenFileDialog and ColorDialog.
Dialog components
3. Choose the openFileDialog1 icon in the area at the bottom of the Windows Forms Designer. Set two
properties:
Set the Filter property to the following (you can copy and paste it):
To continue or review
To go to the next tutorial step, see Step 8: Write Code for the Show a Picture Button Event Handler.
To return to the previous tutorial step, see Step 6: Name Your Button Controls.
Step 8: Write Code for the Show a Picture Button
Event Handler
10/18/2017 • 5 min to read • Edit Online
In this step, you make the Show a picture button work like this:
When a user chooses that button, the program opens an Open File dialog box.
If a user opens a picture file, the program shows that picture in the PictureBox.
The IDE has a powerful tool called IntelliSense that helps you write code. As you enter code, the IDE opens a
box with suggested completions for partial words that you enter. It tries to determine what you want to do
next, and automatically jumps to the last item you choose from the list. You can use the up or down arrows
to move in the list, or you can keep typing letters to narrow the choices. When you see the choice you want,
choose the TAB key to select it. Or, you can ignore the suggestions, if not needed.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 4 or
Tutorial 1: Create a Picture Viewer in C# - Video 4. These videos use an earlier version of Visual Studio, so
there are slight differences in some menu commands and other user interface elements. However, the
concepts and procedures work similarly in the current version of Visual Studio.
To write code for the Show a picture button event handler
1. Go to Windows Forms Designer and double-click the Show a picture button. The IDE immediately goes to
the code designer and moves your cursor so it's inside the showButton_Click() method that you added
previously.
2. Type an i on the empty line between the two braces { }. (In Visual Basic, type on the empty line between
Private Sub... and End Sub.) An IntelliSense window opens, as shown in the following picture.
NOTE
The IntelliSense window can show you both properties and methods. To determine what is being shown,
look at the icon on the left side of each item in the IntelliSense window. You see a picture of a block next to
each method, and a picture of a wrench (or spanner) next to each property. There's also a lightning bolt icon
next to each event. These pictures display as follows.
Method icon
Property icon
Event icon
d. Start to type ShowDialog (capitalization is unimportant to IntelliSense). The ShowDialog() method
will show the Open File dialog box. After the window has highlighted ShowDialog, choose the TAB
key. You can also highlight "ShowDialog" and choose the F1 key to get help for it.
To learn more about the ShowDialog() method, see ShowDialog Method.
e. When you use a method on a control or a component (referred to as calling a method), you need to
add parentheses. So enter opening and closing parentheses immediately after the "g" in ShowDialog :
() It should now look like "openFileDialog1.ShowDialog()".
NOTE
Methods are an important part of any program, and this tutorial has shown several ways to use methods.
You can call a component's method to tell it to do something, like how you called the OpenFileDialog
component's ShowDialog() method. You can create your own methods to make your program do things,
like the one you're building now, called the showButton_Click() method, which opens a dialog box and a
picture when a user chooses a button.
f. For Visual C#, add a space, and then add two equal signs ( == ). For Visual Basic, add a space, and
then use a single equal sign ( = ). (Visual C# and Visual Basic use different equality operators.)
g. Add another space. As soon as you do, another IntelliSense window opens. Start to type
DialogResult and choose the TAB key to add it.
NOTE
When you write code to call a method, sometimes it returns a value. In this case, the OpenFileDialog
component's ShowDialog() method returns a DialogResult value. DialogResult is a special value that tells
you what happened in a dialog box. An OpenFileDialog component can result in the user choosing OK or
Cancel, so its ShowDialog() method returns either DialogResult.OK or DialogResult.Cancel.
h. Type a dot to open the DialogResult value IntelliSense window. Enter the letter O and choose the
TAB key to insert OK.
To learn more about DialogResult , see DialogResult.
NOTE
The first line of code should be complete. For Visual C#, it should be the following.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
i. Now add one more line of code. You can type it (or copy and paste it), but consider using IntelliSense
to add it. The more familiar you are with IntelliSense, the more quickly you can write your own code.
Your final showButton_Click() method looks like the following. (Choose the VB tab to view the Visual
Basic version of the code.)
End Sub
To continue or review
To go to the next tutorial step, see Step 9: Review, Comment, and Test Your Code.
To return to the previous tutorial step, see Step 7: Add Dialog Components to Your Form.
Step 9: Review, Comment, and Test Your Code
10/18/2017 • 5 min to read • Edit Online
You next add a comment to your code. A comment is a note that doesn't change the way the program behaves. It
makes it easier for someone who is reading your code to understand what it does. Adding comments to your code
is a good habit to get into. In Visual C#, two forward slashes (//) mark a line as a comment. In Visual Basic, a single
quotation mark (') is used to mark a line as a comment. After you add a comment, you test your program. It's good
practice to run and test your code frequently while you're working on your projects, so you can catch and fix any
problems early, before the code gets more complicated. This is called iterative testing.
You just built something that works, and although it's not done yet, it can already load a picture. Before you add a
comment to your code and test it, take time to review the code concepts, because you will use these concepts
frequently:
When you double-clicked the Show a picture button in Windows Forms Designer, the IDE automatically
added a method to your program's code.
Methods are how you organize your code: It's how your code is grouped together.
Most of the time, a method does a small number of things in a specific order, like how your
showButton_Click() method shows a dialog box and then loads a picture.
A method is made up of code statements, or lines of code. Think of a method as a way to bundle code
statements together.
When a method is executed, or called, the statements in the method are executed in order, one after
another, starting with the first one.
The following is an example of a statement.
pictureBox1.Load(openFileDialog1.FileName);
pictureBox1.Load(openFileDialog1.FileName)
Statements are what make your programs do things. In Visual C#, a statement always ends in a semicolon.
In Visual Basic, the end of a line is the end of a statement. (No semicolon is needed in Visual Basic.) The
preceding statement tells your PictureBox control to load the file that the user selected with the
OpenFileDialog component.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or
Tutorial 1: Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so
there are slight differences in some menu commands and other user interface elements. However, the
concepts and procedures work similarly in the current version of Visual Studio.
To add comments
1. Add the following comment to your code.
Private Sub showButton_Click() Handles showButton.Click
' Show the Open File dialog. If the user clicks OK, load the
' picture that the user chose.
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
PictureBox1.Load(OpenFileDialog1.FileName)
End If
End Sub
NOTE
Your showButton button's Click event handler is now finished, and it works. You have started writing code, starting
with an if statement. An if statement is how you tell your program, "Check this one thing, and if it's true, do
these actions." In this case, you tell your program to open the Open File dialog box, and if the user selects a file and
chooses the OK button, load that file in the PictureBox.
TIP
The IDE is built to make it easy for you to write code, and code snippets are one way it does that. A snippet is a
shortcut that gets expanded into a small block of code.
You can see all of the snippets available. On the menu bar, choose Tools, Code Snippets Manager. For Visual C#,
the if snippet is in Visual C# . For Visual Basic, the if snippets are in Conditionals and Loops, Code Patterns.
You can use this manager to browse existing snippets or add your own snippets.
To activate a snippet when typing code, type it and choose the TAB key. Many snippets appear in the IntelliSense
window, which is why you choose the TAB key twice: first to select the snippet from the IntelliSense window, and
then to tell the IDE to use the snippet. (IntelliSense supports the if snippet, but not the ifelse snippet.)
2. Before you run your program, save your program by choosing the Save All toolbar button, which appears
as follows.
NOTE
If you don't see any images in the Select a picture file dialog box, be sure that the "All files (*.*)" filter is selected in
the drop-down list on the lower right side of the dialog box.
3. Load a picture, and it appears in your PictureBox. Then try resizing your form by dragging its borders.
Because you have your PictureBox docked inside a TableLayoutPanel, which itself is docked inside the form,
your picture area will resize itself so that it's as wide as the form, and fills the top 90 percent of the form.
That's why you used the TableLayoutPanel and FlowLayoutPanel containers: They keep your form sized
correctly when the user resizes it.
Right now, larger pictures go beyond the borders of your picture viewer. In the next step, you'll add code to
make pictures fit in the window.
To continue or review
To go to the next tutorial step, see Step 10: Write Code for Additional Buttons and a Check Box.
To return to the previous tutorial step, see Step 8: Write Code for the Show a Picture Button Event Handler.
Step 10: Write Code for Additional Buttons and a
Check Box
10/18/2017 • 2 min to read • Edit Online
Now you're ready to complete the other four methods. You could copy and paste this code, but if you want to learn
the most from this tutorial, type the code and use IntelliSense.
This code adds functionality to the buttons you added earlier. Without this code, the buttons don't do anything. The
buttons use code in their Click events (and the check box uses the CheckChanged event) to do different things
when you activate the controls. For example, the clearButton_Click event, which activates when you choose the
Clear the picture button, erases the current image by setting its Image property to null (or, nothing ). Each
event in the code includes comments that explain what the code does.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or Tutorial 1:
Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
NOTE
As a best practice: Always comment your code. Comments are information for a person to read, and it's worth the time to
make your code understandable. Everything on a comment line is ignored by the program. In Visual C#, you comment a line
by typing two forward slashes at the beginning (//), and in Visual Basic you comment a line by starting with a single
quotation mark (').
To continue or review
To go to the next tutorial step, see Step 11: Run Your Program and Try Other Features.
To return to the previous tutorial step, see Step 9: Review, Comment, and Test Your Code.
Step 11: Run Your Program and Try Other Features
10/18/2017 • 2 min to read • Edit Online
Your program is finished and ready to run. You can run your program and set the background color of the
PictureBox. To learn more, try to improve the program by changing the color of the form, customizing the buttons
and check box, and changing the properties of the form.
To download a completed version of the sample, see Complete Picture Viewer tutorial sample.
For a video version of this topic, see Tutorial 1: Create a Picture Viewer in Visual Basic - Video 5 or Tutorial 1:
Create a Picture Viewer in C# - Video 5. These videos use an earlier version of Visual Studio, so there are slight
differences in some menu commands and other user interface elements. However, the concepts and procedures
work similarly in the current version of Visual Studio.
To run your program and set the background color
1. Choose F5, or on the menu bar, choose Debug, Start Debugging.
2. Before you open a picture, choose the Set the background color button. The Color dialog box opens.
NOTE
You can load a picture from the Internet by pasting its URL into the Open File dialog box. Try to find an image with a
transparent background, so your background color shows.
4. Choose the Clear the picture button to make sure it clears. Then, exit the program by choosing the Close
button.
To try other features
Change the color of the form and the buttons by using the BackColor property.
Customize your buttons and check box using the Font and ForeColor properties.
Change your form's FormBorderStyle and ControlBox properties.
Use your form's AcceptButton and CancelButton properties so that buttons are automatically chosen
when the user chooses the ENTER or ESC key. Make the program open the Open File dialog box when the
user chooses ENTER and close the box when the user chooses ESC.
To continue or review
To learn more about programming in Visual Studio, see Programming Concepts.
To learn more about Visual Basic, see Developing Applications with Visual Basic.
To learn more about Visual C#, see Introduction to the C# Language and the .NET Framework.
To go to the next tutorial, see Tutorial 2: Create a Timed Math Quiz.
To return to the previous tutorial step, see Step 10: Write Code for Additional Buttons and a Check Box.
Tutorial 2: Create a Timed Math Quiz
10/18/2017 • 1 min to read • Edit Online
In this tutorial, you build a quiz in which the quiz taker must answer four random arithmetic problems within a
specified time. You learn how to:
Generate random numbers by using the Random class.
Trigger events to occur at a specific time by using a Timer control.
Control program flow by using if else statements.
Perform basic arithmetic operations in code.
When you finish, your quiz will look like the following picture, except with different numbers.
NOTE
This tutorial covers both Visual C# and Visual Basic, so focus on the information that's specific to the programming
language that you're using.
Related Topics
TITLE DESCRIPTION
Step 1: Create a Project and Add Labels to Your Form Start by creating the project, changing properties, and adding
Label controls.
Step 2: Create a Random Addition Problem Create an addition problem, and use the Random class to
generate random numbers.
Step 3: Add a Countdown Timer Add a countdown timer so that the quiz can be timed.
Step 4: Add the CheckTheAnswer() Method Add a method to check whether the quiz taker entered a
correct answer for the problem.
TITLE DESCRIPTION
Step 5: Add Enter Event Handlers for the NumericUpDown Add event handlers that make your quiz easier to take.
Controls
Step 6: Add a Subtraction Problem Add a subtraction problem that generates random numbers,
uses the timer, and checks for correct answers.
Step 7: Add Multiplication and Division Problems Add multiplication and division problems that generate
random numbers, use the timer, and check for correct
answers.
Step 8: Customize the Quiz Try other features, such as changing colors and adding a hint.
Step 1: Create a Project and Add Labels to Your Form
10/18/2017 • 5 min to read • Edit Online
As the first steps in developing this quiz, you create the project, and you add labels, a button, and other controls to
a form. You also set properties for each control that you add. The project will contain the form, the controls, and
(later in the tutorial) code. The button starts the quiz, the labels show the quiz problems, and the other controls
show the quiz answers and the time that remains to finish the quiz.
NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.
NOTE
You can copy the multiplication sign × and the division sign ÷ from this tutorial and paste them onto the form.
7. Set the value of the TabIndex property for the NumericUpDown sum control to 2, for the difference control
to 3, for the product control to 4, and for the quotient control to 5.
The form should look like the following illustration.
In the second part of this tutorial, you make the quiz challenging by adding math problems that are based on
random numbers. You also create a method that's named StartTheQuiz() and that fills in the problems and starts
the countdown timer. Later in this tutorial, you'll add the subtraction, multiplication, and division problems.
NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.
You've added a Random object to your form and named the object randomizer.
Random is known as an object. You've probably heard that word before, and you learn more about what it
means for programming in the next tutorial. For now, just remember that you can use new statements to
create buttons, labels, panels, OpenFileDialogs, ColorDialogs, SoundPlayers, Randoms, and even forms, and
those items are referred to as objects. When you run your program, the form is started, and the code behind
it creates a Random object and names it randomizer.
Soon you'll build a method to check the answers, so your quiz must use variables to store the random
numbers that it generates for each problem. See Variables or Types. To properly use variables, you must
declare them, which means listing their names and data types.
4. Add two integer variables to the form, and name them addend1 and addend2.
NOTE
An integer variable is known as an int in C# or an Integer in Visual Basic. This kind of variable stores a positive or
negative number from -2147483648 through 2147483647 and can store only whole numbers, not decimals.
You use a similar syntax to add an integer variable as you did to add the Random object, as the following
code shows.
5. Add a method that's named StartTheQuiz() and that uses the Random object's Next() method to show the
random numbers in the labels. StartTheQuiz() will eventually fill in all of the problems and then start the
timer, so add a comment. The function should look like the following.
/// <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);
Notice that when you enter the dot (.) after randomizer in the code, an IntelliSense window opens and
shows you all of the Random object's methods that you can call. For example, Intellisense lists the Next()
method, as follows.
Next method
When you enter a dot after an object, IntelliSense shows a list of the object's members, such as properties,
methods, and events.
NOTE
When you use the Next() method with the Random object, such as when you call randomizer.Next(50) , you get
a random number that's less than 50 (from 0 through 49). In this example, you called randomizer.Next(51) . You
used 51 and not 50 so that the two random numbers will add up to an answer that's from 0 through 100. If you
pass 50 to the Next() method, it chooses a number from 0 through 49, so the highest possible answer is 98, not
100. After the first two statements in the method run, each of the two integer variables, addend1 and addend2 ,
hold a random number from 0 through 50. This screenshot shows Visual C# code, but IntelliSense works the same
way for Visual Basic.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();
' Convert the two randomly generated numbers
' into strings so that they can be displayed
' in the label controls.
plusLeftLabel.Text = addend1.ToString()
plusRightLabel.Text = addend2.ToString()
The statements set the Text properties of plusLeftLabel and plusRightLabel so that they display the two
random numbers. You must use the integer's ToString() method to convert the numbers to text. (In
programming, string means text. Label controls display only text, not numbers.
6. In the design window, either double-click the Start button, or choose it and then choose the Enter key.
When a quiz taker chooses this button, the quiz should start, and you've just added a Click event handler to
implement that behavior.
7. Add the following two statements.
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 choose the button during a quiz.
8. Save your code, run it, and then choose the Start button.
A random addition problem appears, as the following illustration shows.
In the third part of this tutorial, you'll add a countdown timer to track the number of seconds that remain for the
quiz taker to finish.
NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.
Now you need a method that actually counts the seconds, such as a timer, which raises an event after the
amount of time that you specify.
2. In the design window, move a Timer control from the Components category of the Toolbox to your form.
The control appears in the gray area at the bottom of the design window.
3. On the form, choose the timer1 icon that you just added, and set its Interval property to 1000.
Because the interval value is milliseconds, a value of 1000 causes the Tick event to fire every second.
4. On the form, double-click the Timer control, or choose it and then choose the Enter key.
The code editor appears and displays the method for the Tick event handler that you just added.
5. Add the following statements to the new event handler method.
End Sub
Based on what you added, the timer checks each second whether time has run out by determining whether
the timeLeft integer variable is greater than 0. If it is, time still remains. The timer first subtracts 1 from
timeLeft and then updates the Text property of the timeLabel control to show the quiz taker how many
seconds remain.
If no time remains, the timer stops and changes the text of the timeLabel control so that it shows Time's
up! A message box announces that the quiz is over, and the answer is revealed—in this case, by adding
addend1 and addend2. The Enabled property of the startButton control is set to true so that the quiz
taker can start another quiz.
You just added an if else statement, which is how you tell programs to make decisions. An if else
statement looks like the following.
NOTE
The following example is for illustration only-don't add it to your project.
Look closely at the statement that you added in the else block to show the answer to the addition problem.
The statement addend1 + addend2 adds the values in the two variables together. The first part ( sum.Value )
uses the Value property of the sum NumericUpDown control to display the correct answer. You use the same
property later to check the answers for the quiz.
Quiz takers can enter numbers more easily by using a NumericUpDown control, which is why you use one for
the answers to the math problems. All of the potential answers are whole numbers from 0 through 100. By
leaving the default values of the Minimum, Maximum, and DecimalPlaces properties, you ensure that
quiz takers can't enter decimals, negative numbers, or numbers that are too high. (If you wanted to allow
quiz takers to enter 3.141 but not 3.1415, you could set the DecimalPlaces property to 3.)
6. Add three lines to the end of the StartTheQuiz() method, so the code looks like the following.
''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()
End Sub
/// <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);
Now, when your quiz starts, the timeLeft variable is set to 30 and the Text property of the timeLabel
control is set to 30 seconds. Then the Start() method of the Timer control starts the countdown. (The quiz
doesn't check the answer yet—that comes next.)
7. Save your program, run it, and then choose the Start button on the form.
The timer starts to count down. When time runs out, the quiz ends, and the answer appears. The following
illustration shows the quiz in progress.
In the fourth part of this tutorial, you'll write a method, CheckTheAnswer() , that determines whether the answers to
the math problems are correct. This topic is part of a tutorial series about basic coding concepts. For an overview of
the tutorial, see Tutorial 2: Create a Timed Math Quiz.
NOTE
If you're following along in Visual Basic, you'll use the Function keyword instead of the usual Sub keyword because this
method returns a value. It's really that simple: a sub doesn't return a value, but a function does.
''' <summary>
''' Check the answer to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean
End Function
/// <summary>
/// Check the answer 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)
return true;
else
return false;
}
Next, you'll check the answer by updating the code in the method for the timer's Tick event handler to call
the new CheckTheAnswer() method.
2. Add the following code to the if else statement.
Private Sub Timer1_Tick() Handles Timer1.Tick
If CheckTheAnswer() Then
' If CheckTheAnswer() returns true, then the user
' got the answer right. Stop the timer
' and show a MessageBox.
Timer1.Stop()
MessageBox.Show("You got all of the answers right!", "Congratulations!")
startButton.Enabled = True
ElseIf timeLeft > 0 Then
' If CheckTheAnswer() return false, keep counting
' down. Decrease the time left by one second and
' display the new time left by updating the
' Time Left label.
timeLeft -= 1
timeLabel.Text = timeLeft & " seconds"
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
startButton.Enabled = True
End If
End Sub
If the answer is correct, CheckTheAnswer() returns true . The event handler stops the timer, shows a
congratulatory message, and then makes the Start button available again. Otherwise, the quiz continues.
3. Save your program, run it, start a quiz, and provide a correct answer to the addition problem.
NOTE
When you enter your answer, you must either select the default value before you start to enter your answer, or you
must delete the zero manually. You'll correct this behavior later in this tutorial.
When you provide a correct answer, a message box opens, the Start button becomes available, and the
timer stops.
To continue or review
To go to the next tutorial step, see Step 5: Add Enter Event Handlers for the NumericUpDown Controls.
To return to the previous tutorial step, see Step 3: Add a Countdown Timer.
Step 5: Add Enter Event Handlers for the
NumericUpDown Controls
10/18/2017 • 4 min to read • Edit Online
In the fifth part of this tutorial, you'll add Enter event handlers to make entering answers for quiz problems a little
easier. This code will select and clear the current value in each NumericUpDown control as soon as the quiz taker
chooses it and starts to enter a different value.
NOTE
This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a
Timed Math Quiz.
''' <summary>
''' Modify the behavior of the NumericUpDown control
''' to make it easier to enter numeric values for
''' the quiz.
''' </summary>
Private Sub answer_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sum.Enter
End Sub
if (answerBox != null)
{
int lengthOfAnswer = answerBox.Value.ToString().Length;
answerBox.Select(0, lengthOfAnswer);
}
}
This code may look complex, but you can understand it if you look at it step by step. First, look at the top of
the method: object sender in C# or sender As System.Object in Visual Basic. 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. So, in the first line of the method, you specify that the sender isn't just any generic
object but specifically a NumericUpDown control. (Every NumericUpDown control is an object, but not every
object is a NumericUpDown control.) The NumericUpDown control is named answerBox in this method,
because it will be used for all of the NumericUpDown controls on the form, not just the sum
NumericUpDown control. Because you declare the answerBox variable in this method, its scope applies only
to this method. In other words, the variable can be used only within this method.
The next line verifies whether answerBox was successfully converted (cast) from an object to a
NumericUpDown control. If the conversion was unsuccessful, the variable would have a value of null (C#)
or Nothing (Visual Basic). The third line gets the length of the answer that appears in the NumericUpDown
control, and the fourth line selects the current value in the control based on this length. Now, when the quiz
taker chooses the control, Visual Studio fires this event, which causes the current answer to be selected. As
soon as the quiz taker starts to enter a different answer, the previous answer is cleared and replaced with
the new answer.
4. In Windows Forms Designer, choose the difference NumericUpDown control.
5. In the Events page of the Properties dialog box, scroll down to the Enter event, choose the drop-down
arrow at the end of the row, and then choose the answer_Enter event handler that you just added.
6. Repeat the previous step for the product and quotient NumericUpDown controls.
7. Save your program, and then run it.
When you choose a NumericUpDown control, the existing value is automatically selected and then cleared
when you start to enter a different value.
To continue or review
To go to the next tutorial step, see Step 6: Add a Subtraction Problem.
To return to the previous tutorial step, see Step 4: Add the CheckTheAnswer() Method.
Step 6: Add a Subtraction Problem
10/18/2017 • 6 min to read • Edit Online
In the sixth part of this tutorial, you'll add a subtraction problem and learn how to perform the following tasks:
Store the subtraction values.
Generate random numbers for the problem (and be sure that the answer is between 0 and 100).
Update the method that checks the answers so that it checks the new subtraction problem too.
Update your timer's Tick event handler so that the event handler fills in the correct answer when time runs
out.
To add a subtraction problem
1. Add two integer variables for the subtraction problem to your form, between the integer variables for the
addition problem and the timer. The code should look like the following.
''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()
End Sub
/// <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);
To prevent negative answers for the subtraction problem, 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. The
following code chooses a random number from 1 through 100 and stores it in the minuend variable.
You can call the Next() method of the Random class, which you named "randomizer" earlier in this tutorial,
in multiple ways. Methods that you can call in more than one way are referred to as overloaded, and you
can use IntelliSense to explore them. Look again at the tooltip of the IntelliSense window for the Next()
method.
Intellisense window tooltip
The tooltip shows (+ 2 overload(s)), which means that you can call the Next() method in two other ways.
Overloads contain different numbers or types of arguments, so that they work slightly differently from one
another. For example, a method might take a single integer argument, whereas one of its overloads might
take an integer and a string. You choose the correct overload based on what you want it to do. When you
add the code to the StartTheQuiz() method, more information appears in the Intellisense window as soon
as you enter randomizer.Next( . Choose the Up Arrow and Down Arrow keys to cycle through the overloads,
as the following illustration shows.
''' <summary>
''' Check the answers to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean
Return True
Else
Return False
End If
End Function
/// <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))
return true;
else
return false;
}
In Visual C#, && is the logical and operator. In Visual Basic, the equivalent operator is AndAlso . These
operators indicate "If the sum of addend1 and addend2 equals the value of the sum NumericUpDown and if
minuend minus subtrahend equals the value of the difference NumericUpDown." The CheckTheAnswer()
method returns true only if the answers to the addition and the subtraction problems are both correct.
4. Replace the last part of the timer's Tick event handler with the following code so that it fills in the correct
answer when time runs out.
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
difference.Value = minuend - subtrahend
startButton.Enabled = True
End If
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
startButton.Enabled = true;
}
In the seventh part of this tutorial, you'll add multiplication and division problems, but first think about how to
make that change. Consider the initial step, which involves storing values.
To add multiplication and division problems
1. Add four more integer variables to the form.
2. As you did before, modify the StartTheQuiz() method to fill in random numbers for the multiplication and
division problems.
''' <summary>
''' Start the quiz by filling in all of the problem
''' values and starting the timer.
''' </summary>
''' <remarks></remarks>
Public Sub StartTheQuiz()
End Sub
/// <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);
3. Modify the CheckTheAnswer() method so that it also checks the multiplication and division problems.
''' <summary>
''' Check the answers to see if the user got everything right.
''' </summary>
''' <returns>True if the answer's correct, false otherwise.</returns>
''' <remarks></remarks>
Public Function CheckTheAnswer() As Boolean
Return True
Else
Return False
End If
End Function
/// <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;
}
You can't easily enter the multiplication sign (×) and the division sign (÷) using the keyboard, so Visual C#
and Visual Basic accept an asterisk (*) for multiplication and a slash mark (/) for division.
4. Change the last part of the timer's Tick event handler so that it fills in the correct answer when time runs
out.
Else
' If the user ran out of time, stop the timer, show
' a MessageBox, and fill in the answers.
Timer1.Stop()
timeLabel.Text = "Time's up!"
MessageBox.Show("You didn't finish in time.", "Sorry!")
sum.Value = addend1 + addend2
difference.Value = minuend - subtrahend
product.Value = multiplicand * multiplier
quotient.Value = dividend / divisor
startButton.Enabled = True
End If
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
product.Value = multiplicand * multiplier;
quotient.Value = dividend / divisor;
startButton.Enabled = true;
}
In the last part of the tutorial, you'll explore some ways to customize the quiz and expand on what you've already
learned. For example, think about how the program creates random division problems for which the answer is
never a fraction. To learn more, turn the timeLabel control a different color, and give the quiz taker a hint.
To customize the quiz
When only five seconds remain in a quiz, turn the timeLabel control red by setting its BackColor property (
timeLabel.BackColor = Color.Red; ). Reset the color when the quiz is over.
Give the quiz taker a hint by playing a sound when the correct answer is entered into a NumericUpDown
control. (You must write an event handler for each control's ValueChanged() event, which fires whenever the
quiz taker changes the control's value.)
To continue or review
To download a completed version of the quiz, see Complete Math Quiz tutorial sample.
To go to the next tutorial, see Tutorial 3: Create a Matching Game.
To return to the previous tutorial step, see Step 7: Add Multiplication and Division Problems.
Tutorial 3: Create a Matching Game
10/18/2017 • 2 min to read • Edit Online
In this tutorial, you build a matching game, where the player must match pairs of hidden icons. You learn how to:
Store objects, such as icons, in a List object.
Use a foreach loop in Visual C# or a For Each loop in Visual Basic to iterate through items in a list.
Keep track of a form's state by using reference variables.
Build an event handler to respond to events that you can use with multiple objects.
Make a timer that counts down and then fires an event exactly once after being started.
When you finish this tutorial, your program will look like the following picture.
NOTE
In this tutorial, both Visual C# and Visual Basic are covered, so focus on information specific to the programming language
that you're using.
If you get stuck or have programming questions, try posting your question on one of the MSDN forums. See
Visual Basic Forum and Visual C# Forum. Also, there are great, free video learning resources available to you. To
learn more about programming in Visual Basic, see Visual Basic Fundamentals: Development for Absolute
Beginners. To learn more about programming in Visual C#, see C# Fundamentals: Development for Absolute
Beginners.
Related Topics
TITLE DESCRIPTION
Step 1: Create a Project and Add a Table to Your Form Begin by creating the project and adding a
TableLayoutPanel control to keep the controls aligned
properly.
Step 2: Add a Random Object and a List of Icons Add a Random object and a List object, to create a list of
icons.
Step 3: Assign a Random Icon to Each Label Assign the icons randomly to the Label controls, so that
each game is different.
Step 4: Add a Click Event Handler to Each Label Add a Click event handler that changes the color of the label
that is clicked.
Step 5: Add Label References Add reference variables to keep track of which labels are
clicked.
Step 6: Add a Timer Add a timer to the form to keep track of the time that has
passed in the game.
Step 7: Keep Pairs Visible Keep pairs of icons visible, if a matching pair is selected.
Step 8: Add a Method to Verify Whether the Player Won Add a CheckForWinner() method to verify whether the
player won.
Step 9: Try Other Features Try other features, such as changing icons and colors, adding
a grid, and adding sounds. Try making the board bigger and
adjusting the timer.
Step 1: Create a Project and Add a Table to Your
Form
10/18/2017 • 4 min to read • Edit Online
The first step in creating a matching game is to create the project and add a table to your form. The table helps
align the icons into an orderly 4x4 grid. You also set several properties to enhance the appearance of the game
board.
To create a project and add a table to your form
1. On the menu bar, choose File, New, Project.
2. If you're not using Visual Studio Express, you need to select a programming language first. From the
Installed Templates list, choose either Visual C# or Visual Basic.
3. In the list of project templates, choose Windows Forms Application, name the project MatchingGame,
and then choose the OK button.
4. In the Properties window, set the following form properties.
a. Change the form's Text property from Form1 to Matching Game. This text appears at the top of the
game window.
b. Set the size of the form to 550 pixels wide by 550 tall. You can do this either by setting the Size
property to 550, 550, or by dragging the corner of the form until you see the correct size in the
lower-right corner of the integrated development environment (IDE).
5. Display the toolbox by choosing the Toolbox tab on the left side of the IDE.
6. Drag a TableLayoutPanel control from the Containers category in the toolbox, and then set the following
properties for it.
a. Set the BackColor property to CornflowerBlue. To do this, open the BackColor dialog box by
choosing the drop-down arrow next to the BackColor property in the Properties window. Then,
choose the Web tab in the BackColor dialog box to view a list of available color names.
NOTE
The colors are not in alphabetical order, and CornflowerBlue is near the bottom of the list.
b. Set the Dock property to Fill by choosing the drop-down button next to the property and choosing
the large middle button. This spreads the table out so that it covers the entire form.
c. Set the CellBorderStyle property to Inset. This provides visual borders between each cell on the
board.
d. Choose the triangle button in the upper-right corner of the TableLayoutPanel to display its task menu.
e. On the task menu, choose Add Row twice to add two more rows, and then choose Add Column
twice to add two more columns.
f. On the task menu, choose Edit Rows and Columns to open the Column and Row Styles window.
Choose each of the columns, choose the Percent option button, and then set each column's width to
25 percent of the total width. Then select Rows from the drop-down box at the top of the window,
and set each row's height to 25 percent. When you're done, choose the OK button.
Your TableLayoutPanel should now be a 4x4 grid, with sixteen equally sized square cells. These rows
and columns are where the icon images will appear later.
7. Be certain that the TableLayoutPanel is selected in the form editor. To verify this, you should see
tableLayoutPanel1 at the top of the Properties window. If it is not selected, choose the TableLayoutPanel
on the form, or choose it in the dropdown control at the top of the Properties window.
While the TableLayoutPanel is selected, open the toolbox and add a Label control (located in the Common
Controls category) to the upper-left cell of the TableLayoutPanel. The Label control should now be selected
in the IDE. Set the following properties for it.
a. Be sure that the label's BackColor property is set to CornflowerBlue.
b. Set the AutoSize property to False.
c. Set the Dock property to Fill.
d. Set the TextAlign property to MiddleCenter by choosing the drop-down button next to the
property, and then choosing the middle button. This ensures the icon appears in the middle of the
cell.
e. Choose the Font property. An ellipsis (...) button should appear.
f. Choose the ellipsis button, and set the Font value to Webdings, the Font Style to Bold, and the Size
to 72.
g. Set the Text property of the label to the letter c.
The upper-left cell in the TableLayoutPanel should now contain a black box centered on a blue
background.
NOTE
The Webdings font is a font of icons that ships with the Windows operating system. In your matching game,
the player needs to match pairs of icons, so you use this font to display the icons to match. Instead of putting
c in the Text property, try entering different letters to see what icons are displayed. An exclamation point is a
spider, an uppercase N is an eye, and a comma is a chili pepper.
8. Choose your label control and copy it to the next cell in the TableLayoutPanel. (Choose the Ctrl+C keys, or
on the menu bar, choose Edit, Copy.) Then paste it. (Choose the Ctrl+V keys, or on the menu bar, choose
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.
NOTE
If you paste too many times, the IDE adds a new row to the TableLayoutPanel so that it has a place to add your new
label control. You can undo it. To remove the new cell, choose the Ctrl+Z keys, or on the menu bar, choose Edit,
Undo.
Now your form is laid out. It should look like the following picture.
Initial matching game form
To continue or review
To go to the next tutorial step, see Step 2: Add a Random Object and a List of Icons.
To return to the overview topic, see Tutorial 3: Create a Matching Game.
Step 2: Add a Random Object and a List of Icons
10/18/2017 • 4 min to read • Edit Online
In this step, you create a set of matching symbols for the game. Each symbol is added to two random cells in the
TableLayoutPanel on the form. To do this, you use two new statements to create two objects. The first is a Random
object, like the one you used in the math quiz game. It is used in this code to randomly choose cells in the
TableLayoutPanel. The second object, which may be new to you, is a List object which is used to store the
randomly-chosen symbols.
To add a Random object and a list of icons
1. In Solution Explorer, choose Form1.cs if you're using Visual C#, or Form1.vb if you're using Visual Basic,
and then on the menu bar, choose View, Code. As an alternative, you can choose the F7 key or double-click
Form1 in Solution Explorer.
This displays the code module behind Form1.
2. In the existing code, add the following code.
' Use this Random object to choose random icons for the squares
Private random As New Random
If you're using Visual 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 ).
3. When adding the List object, notice the IntelliSense window that opens. The following is a Visual C#
example, but similar text appears when you add a list in Visual Basic.
IntelliSense window
NOTE
The Intellisense window appears only when you enter code manually. If you copy and paste the code, it doesn't
appear.
If you look at the code (and remarks) in small sections, it's easier to understand. Your programs can use
List objects to keep track of many different types of items. A list can hold numbers, true/false values, text,
or other objects. You can even have a List object that holds other List objects. The items in a list are
called elements, and each list only holds one type of element. So, a list of numbers can only hold numbers—
you can't add text to that list. Similarly, you can't add numbers to a list of true/false values.
When you create a List object using a new statement, you need to specify the kind of data you want to
store in it. That's why the tooltip at the top of the IntelliSense window shows the types of elements in the
list. Also, that's what List<string> (in Visual C#) and List(Of String) (in Visual Basic) means: It's a List
object that holds elements of string data type. A string is what your program uses to store text, which is
what the tooltip to the right of the IntelliSense window is telling you.
4. Consider why in Visual Basic a temporary array must be created first, but in Visual C#, the list can be created
with one statement. This is because the Visual C# language has collection initializers, which prepare the list
to accept values. In Visual Basic, you can use a collection initializer. However, for compatibility with the
previous version of Visual Basic, we recommend using the preceding code.
When you use a collection initializer with a new statement, after the new List object is created, the
program fills it with the data you provided inside the curly braces. In this case, you get a list of strings
named icons, and that list will be initialized so that it contains sixteen strings. Each of those strings is a
single letter, and they all correspond to the icons that will be in the labels. So, the game will have a pair of
exclamation points, a pair of uppercase N letters, a pair of commas, and so on. (When these characters are
set to the Webdings font, they will appear as symbols, such as a bus, a bike, a spider, and so forth.) Your
List object will have sixteen strings in all, one for each cell in the TableLayoutPanel panel.
NOTE
In Visual Basic, you get the same result, but first the strings are put into a temporary array, which is then converted
into a List object. An array is similar to a list, except, for example, arrays are created with a fixed size. Lists can
shrink and grow as needed, which is important in this program.
To continue or review
To go to the next tutorial step, see Step 3: Assign a Random Icon to Each Label.
To return to the previous tutorial step, see Step 1: Create a Project and Add a Table to Your Form.
Step 3: Assign a Random Icon to Each Label
10/18/2017 • 6 min to read • Edit Online
If the icons show up in the same cells every game, it's not very challenging. To avoid this, assign the icons
randomly to the label controls on your form by using an AssignIconsToSquares() method.
To assign a random icon to each label
1. Before adding the following code, consider how the method works. There's a new keyword: foreach in
Visual C# and For Each in Visual Basic. (One of the lines is commented out on purpose, which is explained
at the end of this procedure.)
/// <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);
}
}
}
''' <summary>
''' Assign each icon from the list of icons to a random square
''' </summary>
''' <remarks></remarks>
Private Sub AssignIconsToSquares()
End Sub
2. Add the AssignIconsToSquares() method as shown in the previous step. You can put it just below the code
you added in Step 2: Add a Random Object and a List of Icons.
As mentioned earlier, there's something new in your AssignIconsToSquares() method: a foreach loop in
Visual C# and For Each in Visual Basic. You can use a For Each loop any time you want to do the same
action multiple times. In this case, you want to execute the same statements for every label on your
TableLayoutPanel, as explained by the following code. The first line creates a variable named control that
stores each control one at a time while that control has the statements in the loop executed on it.
NOTE
The names "iconLabel" and "control" are used because they are descriptive. You can replace these names with any
names, and the code will work exactly the same as long as you change the name in each statement inside the loop.
The AssignIconsToSquares() method iterates through each label control in the TableLayoutPanel and
executes the same statements for each of them. Those statements pull a random icon from the list that you
added in Step 2: Add a Random Object and a List of Icons. (That's why you included two of each icon in the
list, so there would be a pair of icons assigned to random label controls.)
Look more closely at the code that runs inside the foreach or For Each loop. This code is reproduced here.
The first line converts the control variable to a label named iconLabel . The line after that is an if
statement that checks to make sure the conversion worked. If the conversion does work, the statements in
the if statement run. (As you may recall from the previous tutorials, the if statement is used to evaluate
whatever condition you specify.) 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. To do this, it uses the
Next method of the Random object that you created earlier. 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 icon list items to the Text property of the label. The
commented-out line is explained later in this topic. Finally, the last line in the if statement removes from
the list the icon that has been added to the form.
Remember, if you're not sure about what some part of the code does, you can position the mouse pointer
over a code element and review the resulting tooltip. You can also step through each line of code while the
program is running by using the Visual Studio debugger. See How Do I: Step with The Debugger in Visual
Studio? or Navigating through Code with the Debugger for more information.
3. To fill up the game board with icons, you need to call the AssignIconsToSquares() method as soon as the
program starts. If you're using Visual C#, add a statement just below the call to the InitializeComponent()
method in the Form1 constructor, so your form calls your new method to set itself up before it's shown.
Constructors are called when you create a new object, such as a class or struct. See Constructors (C#
Programming Guide) or Using Constructors and Destructors in Visual Basic for more information.
public Form1()
{
InitializeComponent();
AssignIconsToSquares();
}
For Visual Basic, add the AssignIconsToSquares() method call to the Form1_Load method so that the code
looks like the following.
4. Save your program and run it. It should show a form with random icons assigned to each label.
5. Close your program, and then run it again. Notice that different icons are assigned to each label, as shown in
the following picture.
TIP
Another way to hide controls like labels is to set their Visible property to False .
6. To hide the icons, stop the program and remove the comment marks for the commented line of code inside
the For Each loop.
iconLabel.ForeColor = iconLabel.BackColor;
iconLabel.ForeColor = iconLabel.BackColor
7. On the menu bar, choose the Save All button to save your program, and then run it. The icons seem to have
disappeared—only a blue background appears. However, the icons are randomly assigned and are still
there. Because the icons are the same color as the background, it hides them from the player. After all, it
wouldn't be a very challenging game if the player could see all of the icons right away!
To continue or review
To go to the next tutorial step, see Step 4: Add a Click Event Handler to Each Label.
To return to the previous tutorial step, see Step 2: Add a Random Object and a List of Icons.
Step 4: Add a Click Event Handler to Each Label
10/18/2017 • 3 min to read • Edit Online
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;
}
}
''' <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>
''' <remarks></remarks>
Private Sub label_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Label9.Click,
Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,
Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click,
Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click
clickedLabel.ForeColor = Color.Black
End If
End Sub
NOTE
If you copy and paste the label_Click() code block rather than entering the code manually, be sure to replace the
existing label_Click() code. Otherwise, you'll end up with a duplicate code block.
NOTE
You may recognize object sender at the top of the event handler as the same one used in the Tutorial 2: Create a
Timed Math Quiz tutorial. Because you hooked up different label control Click event to a single event handler
method, the same method is called no matter which label the user chooses. The event handler method needs to
know which label was chosen, so it uses the name sender to identify the label control. The first line of the method
tells the program that it's not just a generic object, but specifically a label control, and that it uses the name
clickedLabel to access the label's properties and methods.
This method first checks whether clickedLabel was successfully converted (cast) from an object to a label
control. If unsuccessful, it has a value of null (C#) or Nothing (Visual Basic), and you don't want to execute
the remainder of the code in the method. Next, the method checks the chosen label's text color by using the
label's ForeColor property. If the label's text color is black, then that means the icon's already been chosen
and the method is done. (That's what the return statement does: It tells the program to stop executing the
method.) Otherwise, the icon hasn't been chosen, so the program changes the label's text color to black.
6. On the menu bar, choose File, Save All to save your progress, and then, on the menu bar, choose 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, and one of the icons should become visible. Continue choosing different places in
the form. As you choose the icons, they should appear.
To continue or review
To go to the next tutorial step, see Step 5: Add Label References.
To return to the previous tutorial step, see Step 3: Assign a Random Icon to Each Label.
Step 5: Add Label References
10/18/2017 • 4 min to read • Edit Online
The program needs to track which label controls the player chooses. Right now, the program shows all labels
chosen by the player. But we're going to change that. After the first label is chosen, the program should show the
label's icon. After the second label is chosen, the program should display both icons for a brief time, and then hide
both icons again. Your program will now keep track of which label control is chosen first and which is chosen
second by using reference variables.
To add label references
1. Add label references to your form by using the following code.
These reference variables look similar to the statements you used earlier to add objects (like Timer objects,
List objects, and Random objects) to your form. However, these statements don't cause two extra label
controls to appear on the form because there's no new keyword used in either of the two statements.
Without the new keyword, no object is created. That's why firstClicked and secondClicked are called
reference variables: They just keep track (or, refer to) Label objects.
When a variable isn't keeping track of an object, it's set to a special reserved value: null in Visual C# and
Nothing in Visual Basic. So, when the program starts, both firstClicked and secondClicked are set to
null or Nothing , which means that the variables aren't keeping track of anything.
2. Modify your Click event handler to use the new firstClicked reference variable. Remove the last statement
in the label_Click() event handler method ( clickedLabel.ForeColor = Color.Black; ) and replace it with the
if statement that follows. (Be sure you include the comment, and the whole if statement.)
''' <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>
''' <remarks></remarks>
Private Sub label_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Label9.Click,
Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click,
Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click,
Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click
End Sub
/// <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 label_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.
4. Choose the next label control, and notice that nothing happens. The program is already keeping track of the
first label that the player chose, so firstClicked isn't equal to null in Visual C# or Nothing in Visual Basic.
When your if statement checks firstClicked to determine if it's equal to null or Nothing , it finds that it
isn't, and it doesn't execute the statements in the if statement. So, only the first icon that's chosen turns
black, and the other icons are invisible, as shown in the following picture.
Next, you add a Timer control to the matching game. A timer waits a specified number of milliseconds, and then
fires an event, referred to as a tick. This is useful for starting an action, or repeating an action on a regular basis. In
this case, you'll use a timer to enable players to choose two icons, and if the icons don't match, hide the two icons
again after a short period of time.
To add a timer
1. From the toolbox in Windows Forms Designer, choose Timer (in the Components category) and then
choose the ENTER key, or double-click the timer to add a timer control to the form. The timer's icon, called
Timer1, should appear in a space below the form, as shown in the following picture.
Timer
NOTE
If the toolbox is empty, be sure to select the form designer, and not the code behind the form, before opening the
toolbox.
2. Choose the Timer1 icon to select the timer. In the Properties window, switch from viewing events to
viewing properties. Then, set the timer's Interval property to 750, but leave its Enabled property set to
False. The Interval property tells the timer how long to wait between ticks, or when it triggers its Tick event.
A value of 750 tells the timer to wait three quarters of a second (750 milliseconds) before it fires its Tick
event. You'll call the Start() method to start the timer only after the player chooses the second label.
3. Choose the timer control icon in Windows Forms Designer and then choose the ENTER key, or double-click
the timer, to add an empty Tick event handler. Either replace the code with the following code, or manually
enter the following code into the event handler.
/// <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();
''' <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>
''' <remarks></remarks>
Private Sub Timer1_Tick() Handles Timer1.Tick
End Sub
The Tick event handler does three things: First, it makes sure the timer isn't running by calling the Stop()
method. Then it uses two reference variables, firstClicked and secondClicked , to make the icons of the
two labels that the player chose invisible again. Finally, it resets the firstClicked and secondClicked
reference variables to null in Visual C# and Nothing in Visual Basic. This step is important because it's
how the program resets itself. Now it's not keeping track of any Label controls, and it's ready for the player
to choose a label again.
NOTE
A Timer object has a Start() method that starts the timer, and a Stop() method that stops it. When you set
the timer's Enabled property to True in the Properties window, it starts ticking as soon as the program begins. But
when you leave it set to False, it doesn't start ticking until its Start() method is called. Normally, a timer fires its
Tick event over and over again, using the Interval property to determine how many milliseconds to wait between
ticks. You may have noticed how the timer's Stop() method is called inside the Tick event. That puts the timer into
one shot mode, meaning that when the Start() method is called, it waits for the specified interval, triggers a single
Tick event, and then stops.
4. To see the new timer in action, go to the code editor and add the following code to the top and bottom of
the label_Click() event handler method. (You're adding an if statement to the top, and three statements
to the bottom; the rest of the method stays the same.)
/// <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 label_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;
End Sub
The code at the top of the method checks whether the timer was started by checking the value of the
Enabled property. That way, 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 that the player chose, and then it sets that label's 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 event. The timer's
Tick event handler hides the two icons and resets the firstClicked and secondClicked reference variables
so the form is ready for the player to choose another pair of icons.
5. Save and run your program. Choose an icon, and it becomes visible.
6. Choose another icon. It appears briefly, and then both icons disappear. Repeat this numerous times. The
form now keeps track of the first and second icons that you choose, and uses the timer to pause before
making the icons disappear.
To continue or review
To go to the next tutorial step, see Step 7: Keep Pairs Visible.
To return to the previous tutorial step, see Step 5: Add Label References.
Step 7: Keep Pairs Visible
10/18/2017 • 3 min to read • Edit Online
The game works well, as long as the player only chooses pairs of icons that don't match. But consider what should
happen when the player chooses a matching pair. Instead of making the icons disappear by turning on the timer
(using the Start() method), the game should reset itself so that it's no longer keeping track of any labels using
the firstClicked and secondClicked reference variables, without resetting the colors for the two labels that were
chosen.
To keep pairs visible
1. Add the following if statement to the label_Click() event handler method, near the end of the code just
above the statement where you start the timer. Take a close look at the code while adding it to the program.
Consider how the code works.
The first line of the if statement you just added 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 identical, the program executes the three
statements between the curly braces in C# or the three statements within the if statement in Visual Basic.
The first two statements reset the firstClicked and secondClicked reference variables so that they no
longer keep track of any of the labels. (You may recognize those two statements from the timer's Tick event
handler.) The third statement is a return statement, which tells the program to skip the rest of the
statements in the method without executing them.
If programming in Visual C#, you may have noticed that some of the code uses a single equal sign ( = ),
while other statements use two equal signs ( == ). Consider why = is used in some places but == is used in
other places.
This is a good example that shows the difference. Take a careful look at the code between the parentheses in
the if statement.
firstClicked.Text = secondClicked.Text
firstClicked.Text == secondClicked.Text
Then look closely at the first statement in the block of code after the if statement.
firstClicked = Nothing
firstClicked = null;
The first of those two statements checks whether two icons are the same. Because two values are being
compared, the Visual C# program uses the == equality operator. The second statement actually changes
the value (called assignment), setting the firstClicked reference variable equal to null to reset it. That's
why it uses the = assignment operator instead. Visual C# uses = to set values, and == to compare them.
Visual Basic uses = for both variable assignment and comparison.
2. Save and run the program, and then start choosing icons on the form. If you choose a pair that doesn't
match, the timer's Tick event triggers, and both icons disappear. If you choose a matching pair, the new if
statement executes, and the return statement causes the method to skip the code that starts the timer, so the
icons stay visible, as shown in the following picture.
You've created a fun game, but it needs an additional item to finish it. The game should end when the player wins,
so you need to add a CheckForWinner() method to verify whether the player won.
To add a method to verify whether the player won
1. Add a CheckForWinner() method to the bottom of your code, below the timer1_Tick() event handler, as
shown in the following code.
/// <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;
}
}
End Sub
The method uses another foreach loop in Visual C# or For Each loop in Visual Basic to go through each
label in the TableLayoutPanel. It uses the equality operator ( == in Visual C# and = in Visual Basic) to check
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 icons remaining. 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 form's Close() method to end the
game.
2. Next, have the label's Click event handler call the new CheckForWinner() method. 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, as
shown in the following code.
3. Save and run the program. Play the game and match all of the icons. When you win, the program displays a
congratulatory MessageBox (as shown in the following picture), and then closes the box.
To learn more, try changing icons and colors, adding a game timer, and adding sounds. To make the game more
challenging, try making the board bigger and adjusting the timer.
To download a completed version of the sample, see Complete Matching Game tutorial sample.
To try other features
Replace the icons and colors with ones you choose.
TIP
Try looking at the label's Forecolor property.
Add a game timer that tracks how long it takes for the player to win.
TIP
To do this, you can add a label to display the elapsed time on the form above the TableLayoutPanel, and 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.
TIP
To play sounds, you can use the System.media namespace. See Play Sounds in Windows Forms App (C# .NET) or How
To Play Audio In Visual Basic for more information.
TIP
You'll need to do more than just add rows and columns to the TableLayoutPanel - you'll 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 and doesn't
choose the second icon before a certain amount of time.
To continue or review
If you get stuck or have programming questions, try posting your question on one of the MSDN forums. See
Visual Basic Forum and Visual C# Forum.
There are great, free video learning resources available to you. To learn more about programming in Visual
Basic, see Visual Basic Fundamentals: Development for Absolute Beginners. To learn more about
programming in Visual C#, see C# Fundamentals: Development for Absolute Beginners.
To return to the previous tutorial step, see Step 8: Add a Method to Verify Whether the Player Won.
Getting Started with C++ in Visual Studio
10/18/2017 • 4 min to read • Edit Online
By completing this walkthrough, you'll become familiar with many of the tools and dialog boxes that you can use
when you develop applications with Visual Studio. You'll create a simple "Hello, World"-style application while you
learn more about working in the integrated development environment (IDE).
This topic contains the following sections:
Sign In to Visual Studio
Create a simple application
Add Code to the Application
Debug and Test the application
Build a release version of the app
After you open Visual Studio, you can see the three basic parts of the IDE: tool windows, menus and toolbars, and
the main window space. Tool windows are docked on the left and right sides of the app window, with Quick
Launch, the menu bar, and the standard toolbar at the top. The center of the application window contains the Start
Page. When you open a solution or project, editors and designers appear in this space. When you develop an
application, you'll spend most of your time in this central area.
2. In the Visual C++ category, choose the Win32 Console Application template, and then name the project
GreetingsConsoleApp .
Your dialog box may have different choices, depending on what you've installed. If you don't see Visual C++
project templates, you need to go back to the installer and install a C++ workload.
3. When the Win32 Application Wizard appears, choose the Finish button.
The GreetingsConsoleApp project and solution, with the basic files for a Win32 console app, are created and
automatically loaded into Solution Explorer. The GreetingsConsoleApp.cpp file is opened in the code
editor. The following items appear in Solution Explorer:
Figure 4: Project items
A red squiggly line appears under cout . An error message appears if you point to it.
The error message also appears in the Error List window. You can display the window by choosing View,
Error List on the menu bar.
cout is included in the <iostream> header file.
2. To include the iostream header, enter the following code after #include "stdafx.h" :
#include <iostream>
using namespace std;
You probably noticed that a box appeared as you entered code, providing suggestions for the characters
that you entered. This box is part of C++ IntelliSense, which provides coding prompts, including listing class
or interface members and parameter information. You can also use code snippets, which are pre-defined
blocks of code. For more information, see Using IntelliSense and Code Snippets.
The red squiggly line under cout disappears when you fix the error.
3. Save the changes to the file.
A red circle appears next to the line of code in the far left margin of the editor window.
2. Choose the F5 key to start debugging.
The debugger starts, and a console window appears showing the word Hello.
3. Press SHIFT + F5 to stop debugging.
For more information, see Console Projects.
See Also
Using the Visual Studio IDE for C++ Desktop Development
Walkthrough: Create a Simple Application with Visual C# or Visual Basic
Productivity Tips for Visual Studio
Visual Studio Samples
Get Started Developing with Visual Studio
Getting Started with Debugging in Visual Studio
10/18/2017 • 11 min to read • Edit Online
Visual Studio provides a powerful integrated set of project build and debugging tools. In this topic, find out how to
start using the most basic set of debugging UI features.
Note: Links to more advanced features and platform- or feature-specific topics are at the bottom of this page.
You can also specify a specific build platform to target, such as x86 (32-bit Intel CPUs), x64 (64-bit Intel CPUs), and
ARM (ARM CPUs, only supported for certain app types). The default is x86 for managed and native projects. To
change it, click on build platform dropdown and select a different platform or Configuration Manager...
You can specify a targeted build configuration using the Configuration Manager. Launch it, click the
Configuration or the CPU dropdown, and select New... to create a new build or platform.
Starting out, just use Debug and x86 as your build configuration and platform, respectively. When you're done
coding and debugging, change the configuration to Release and target a specific platform. (Older versions of
Visual Studio provided an AnyCPU default platform for .Net code projects.)
Note: When you build your project, the configuration and platform values are also used to determine what project
directory path is created to store the executable. Typically, this is <path-to-project>\\<configuration>\
<platform>. For example, a project with a configuration of Debug and a platform of x86 would be found under
Projects\MyProjectNameHere\MyProjectNameHere\bin\Debug\x86 . This can be useful if you have your own tools or
scripts that manage these built executables.
Building your Code
With your build configured, it's time to actually build your project. The easiest way to do it to press F7, but you can
also start the build by selecting Build->Build Solution from the main menu.
You can observe the build process in the Output status window at the bottom of the Visual Studio UI. Errors,
warnings, and build operations are displayed here. If you have errors (or if you have a warnings above a configured
level), your build will fail. You can click on the errors and warnings to go to the line where they occurred. Rebuild
your project by pressing either F7 again (to recompile only the files with errors) or Ctrl+Alt+F7 (for a clean and
complete rebuild).
There are two build tabbed windows in the results window below the editor: the Output window, which contains
the raw compiler output (including error messages); and the Error List window, which provides a sortable and
filterable list of all errors and warnings.
When successful, you will see results like this in the Output window.
Use Ctrl+G to quickly jump to the line number where the error occurred.
The error is identified by a red "squiggle" underscore. Hover over it for additional details. Make the fix and it will go
away, although you may introduce a new error with the correction. (This is called a "regression".)
Walk through the error list and address all the errors in your code.
Reviewing Errors in Detail
Many errors may make no sense to you, phrased as they are in the terms of the compiler. In those cases, you will
need additional information. From the Error List window, you can do an automatic Bing search for more
information on the error (or warning) by right-clicking on the corresponding entry line and selecting Show Error
Help from the context menu.
This launches a tab inside Visual Studio that hosts the results of a Bing search for the error code and text. The
results are from many different sources on the Internet, and not all may be helpful.
Alternatively, you can click on the hyperlinked error code value in the Code column of the Error List. This will
launch a Bing search for just the error code.
Performing Static Code Analysis
"Static code analysis" is a fancy way of saying "automatically check my code for common problems that can lead to
run-time errors or problems in code management". Get in the habit of running it once you've cleaned up the
obvious errors preventing build, and take some time to address the warnings it may produce. You'll save yourself
some headaches down the road, as well as learn a few code style techniques.
Press Alt+F11 (or select Analyze->Run Code Analysis on Solution from the top menu) to start static code
analysis. This may take some time if you have a lot of code.
Any new or updated warnings will appear in the Error List tab at the bottom of the IDE. Click on the warnings to
jump to them.
The warnings will be identified with a bright yellow-green squiggle instead of a red one. Hover over them for more
detail, and right-click on them to get a context menu to assist in fixes or refactoring options.
You will see a list of possible fixes or refactors you can apply to that line of code.
Light Bulbs can be used wherever the code analyzers determine there is an opportunity to fix, refactor, or improve
your code. Click on any line of code, right-click to open the context menu, and select Quick Options (or, again, if
you prefer efficiency, press Ctrl+.). If there is area refactoring or improvement options available, they will be
displayed; otherwise, the message No quick options available here will be displayed in the lower-left corner bezel
of the IDE.
With experience, you can quickly use the arrow keys and Ctrl+. to check for Quick Option refactoring opportunities
and clean up your code!
For more information on Light Bulbs, read Perform quick actions with light bulbs.
Debugging Your Running Code
Now that you've successfully built your code and performed a little clean up, run it by pressing F5 or selecting
Debug->Start Debugging. This will start your app in a debug environment so you can observe its behavior in
detail. The Visual Studio IDE changes while your app is running: the Output window is replaced by two new ones
(in the default window configuration), the Autos/Locals/Modules/Watch tabbed window and the Call
Stack/Breakpoints/Exception Settings/Output tabbed window. These windows have multiple tabs which allow
you to inspect and evaluate your app's variables, threads, call stacks, and various other behaviors as it runs.
Try various actions with your app and observe the changes. If something appears abnormal, pause the app by
pressing Ctrl+Alt+Break (or click on the Pause button).
Press F5 to continue running the app (or click the Continue button).
You can stop your app by pressing Shift+F5 or by clicking the Stop button. Or, you can simply close the app's main
window (or command line dialog).
If your code ran perfectly and exactly as expected, congratulations! Change the build configuration to Release and
rebuild it for deployment! (Professionals may want to jump to the bit on Unit Testing at the end, though.) However,
if it hung, or crashed, or gave you some strange results, you'll need to find the source of those problems and fix the
bugs.
Setting Simple Breakpoints
Breakpoints are the most basic and essential feature of reliable debugging. A breakpoint indicates where Visual
Studio should suspend your running code so you can take a look at the values of variables, or the behavior of
memory, or whether or not a branch of code is getting run. You do NOT need to rebuild a project after setting and
removing breakpoints.
Set a breakpoint by clicking in the far margin of the line where you want the break to occur, or select the line of
code and press F9. When you run your code, it will stop before the instructions for this line of code are executed.
When the code breaks, the marked line of code has not executed yet. At this point, you may want to execute the
instructions for the line of code marked by the breakpoint and inspect the changed values. This is called "stepping
into" the code. If the marked code is a method call, you can step into it by pressing F11. You can also "step over"
the line of code by pressing F10. For more details on code stepping, read Navigating through Code with the
Debugger.
Common uses for breakpoints include:
1. To narrow down the source of a crash or hang, scatter them throughout and around the code of the method
call you think is causing the failure. As you step through the code, remove and then reset the breakpoints
closer together until you find the offending line of code.
2. When you introduce new code, set a breakpoint at the beginning of it and step through the code to make
sure it is behaving as expected.
3. If you have implemented a complicated behavior, set breakpoint(s) for the algorithmic code so you can
inspect the values of the variables and data when the program breaks.
4. If you are writing C or C++ code, use breakpoints to stop the code so you can inspect address values (look
for NULL) and reference counts when debugging for memory-related failures.
For more information on using breakpoints, read Using Breakpoints
Setting Conditional Breakpoints
If you have a breakpoint in a loop or recursion, or if you have a lot of breakpoints which you frequently step
through, use a conditional breakpoint to ensure that your code is suspended ONLY when specific conditions are
met. Otherwise, you'll be pressing F11 an awful lot.
To set a conditional breakpoint and suspend your code when a variable is set to a certain value or passes a certain
threshold, click in the margin to set a breakpoint, and then select the "cog" from the hover menu that appears.
You will see a dialog that looks like this where you can set specific conditions for the break to occur.
For more detail on how to declare the expressions used to evaluate conditional breakpoints, check out the
Channel9 video Breakpoint Configuration Experience in Visual Studio.
Inspecting Your Code at Run-time
When your running code hits a breakpoint and halts, you can inspect your variables and call stacks to determine
what is going on. Are the values in the ranges you expect to see? Are calls being made in the right order?
Hover over a variable to see the value(s) and reference(s) it currently contains. If you see a value you didn't expect,
you probably have a bug in the preceding or calling lines of code. Move breakpoints up or add conditions to the
existing breakpoints to narrow your search further.
Additionally, Visual Studio displays the Diagnostic Tools window, where you can observe your app's CPU and
memory usage over time. Use them to look for unanticipated heavy CPU usage or memory allocation. Use it in
conjunction with the Watch window and breakpoints to determine what's causing unexpected heavy usage or
unreleased resources.
Running Unit Tests
Unit tests are programs that exercise code paths in your app or service. Visual Studio installs the Microsoft unit
testing frameworks for both managed and native code. Use a unit testing framework to create unit tests, run them,
and report the results of these tests. Rerun unit tests when you make changes to test that your code is still working
correctly. When you use Visual Studio Enterprise edition, you can run tests automatically after every build.
To get started, read Generate unit tests for your code with IntelliTest.
To learn more about unit tests in Visual Studio and how they can help you create better quality code, read Unit Test
Basics.
See Also
Debugger Feature Tour
Debugger Settings and Preparation
Debug 64-Bit Applications
Debugger Basics
How to: Move Around in the Visual Studio IDE
10/18/2017 • 4 min to read • Edit Online
The integrated development environment (IDE) has been designed to allow you to move from window to window
and file to file in several different ways, depending on your preference or project requirements. You can choose to
cycle through open files in the editor, or cycle through all active tool windows in the IDE. You also can switch
directly to any file open in the editor, regardless of the order in which it was last accessed. These features can help
increase your productivity when working in the IDE.
NOTE
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is
described in Help depending on your active settings or edition. This Help page was written with General Development
Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information,
see Personalize the Visual Studio IDE.
Keyboard Shortcuts
Almost every menu command in Visual Studio has a keyboard shortcut. You can also create your own custom
shortcuts. For more information, see Identifying and Customizing Keyboard Shortcuts.
NOTE
Navigate Backward and Navigate Forward also can be found on the View menu.
You also can switch to a specific file open in the editor, regardless of when you last accessed the file, using
the IDE Navigator, the Active Files list in the editor, or the Windows dialog box.
The IDE Navigator works much like the Windows application switcher. It is not available from menus and
can be accessed only using shortcut keys. You can use either of two commands to access the IDE Navigator
(shown below) to cycle through files, depending on the order in which you want to cycle through.
Window.PreviousDocumentWindowNavallows you to move to the file most recently accessed and
Window.NextDocumentWindowNav allows you to move in the reverse order. General Development Settings
assigns CTRL + SHIFT + TAB to Window.PreviousDocumentWindowNav and CTRL + TAB to
Window.NextDocumentWindowNav .
NOTE
If the settings combination you are using does not already have a shortcut key combination assigned to this command, you
can assign your own custom command using the Keyboard page of the Options dialog box. For more information, see
Identifying and Customizing Keyboard Shortcuts.
TIP
To reverse the order in which you go through the Active Files list, hold down the CTRL + SHIFT keys and press TAB.
- or -
In the upper right corner of the editor, choose the Active Files button, and then select a file from the list to
switch to.
- or -
On the menu bar, choose Window, Windows.
In the list, select the file you want to view and then choose Activate.
TIP
To reverse the order in which you go through the Active Tool Windows list, hold down the SHIFT + ALT keys and
press F7.
See Also
Customizing window layouts
Default Keyboard Shortcuts
Optimize Visual Studio performance
10/24/2017 • 3 min to read • Edit Online
Visual Studio is designed to start up as quickly and efficiently as possible. However, certain Visual Studio extensions
and tool windows can adversely affect startup time when they are loaded. You can control the behavior of slow
extensions and tool windows in the the Manage Visual Studio Performance dialog box. For more general tips on
improving performance, see Visual Studio Performance Tips and Tricks.
Startup behavior
To avoid extending startup time, Visual Studio 2017 loads extensions using an on demand approach. This behavior
means that extensions don't open immediately after Visual Studio starts, but on an as-needed basis. Also, because
tool windows left open in a prior Visual Studio session can slow startup time, Visual Studio opens tool windows in a
more intelligent way to avoid impacting startup time.
If Visual Studio detects slow startup, a pop-up message appears, alerting you to the extension or tool window that's
causing the slowdown. The message provides a link to the Manage Visual Studio Performance dialog box. You
can also access this dialog box by choosing Help, Manage Visual Studio Performance from the menu bar.
The dialog box lists the extensions and tools windows that are affecting startup performance. You can change
extension and tool window settings to improve startup performance.
To configure global settings for lightweight solution load, see Optimize solution loading.
See Also
Visual Studio Performance Tips and Tricks
Optimize Solution Loading in Visual Studio
10/18/2017 • 7 min to read • Edit Online
Many solutions contain a large number of projects, which affects the time taken to load those solutions. However,
in team environments, developers typically work on a different subset of those projects and don’t need to load all
of the individual projects.
Visual Studio 2017 supports lightweight solution load. When lightweight solution load (LSL) mode is enabled,
Visual Studio 2017 loads a small subset of projects instead of loading all the projects in a large solution. Most of
the commonly used IDE features work under LSL mode, and it provides the ability for you to build, search, and
debug on the entire solution. (The main unsupported feature in LSL mode is edit and continue).
NOTE
This content applies to Visual Studio 2017 Update 3
For large solutions with more than 30 projects, LSL typically loads solutions twice as fast (on average). While most
of the IDE features work in LSL mode, some IDE features might require all the projects to be loaded. In these cases,
Visual Studio automatically loads the entire solution so that you can use the feature. In the worst-case scenario,
you end up loading all the projects in the lightweight mode.
If you use an IDE feature on a project that is not currently loaded, Visual Studio loads the appropriate project(s) for
you. For example, if you are trying to create or open a class diagram for an unopened project, Visual Studio
automatically loads the appropriate projects. The detailed feature list is referenced in the sections following.
The following sections show how to enable lightweight solution load and also help you decide whether or not to
enable the feature.
NOTE
Similar steps apply for disabling LSL. To disable lightweight solution load, select Disable Lightweight Solution Load, then
close and reopen the solution.
Configure global settings for lightweight solution load
You can globally disable or configure LSL for all the solutions by choosing Tools > Options > Projects and
Solutions.
IntelliSense Yes
Search Yes
Debugging Yes
Build Yes
Multi-targeting Yes
FEATURE SUPPORTED IN LIGHTWEIGHT MODE?
IntelliTrace Yes
IntelliTest Yes
CATEGORY ISSUE
Unit test Projects that are not currently loaded do not show up in the
list of test projects for both the “Create IntelliTest” and “Create
Unit Test” wizards.
You need to load the projects for which you want to create
tests (you can expand the project node to load the project).
CATEGORY SCENARIO
TFS SCC command on solution node If an SCC command is triggered on the solution node (within
Solution Explorer), Visual Studio automatically loads the entire
solution before completing the command.
Project load If your solution contains .NET Core projects and Shared
projects, Visual Studio always automatically loads these
projects during initial solution load itself. These projects do not
currently support lightweight mode.
CATEGORY SCENARIO
Solution configuration manager If you use solution configuration manager or batch build,
Visual Studio automatically loads the entire solution to
provide a full experience.
NuGet package manager If you open NuGet package manager’s user interface, or the
NuGet package manager console, Visual Studio automatically
loads the entire solution to provide a full experience.
Known issues
There are some scenarios that may not work in LSL mode, and require the loading of additional projects or the
entire solution. We are actively working on addressing these cases.
IntelliSense IntelliSense may not get updated after a Reload solution after changing the
configuration change (for example, configuration.
changing a release build to debug and
vice versa). The impact depends on
code differences due to configuration
change.
Refactoring limitations for C#/VB Code fixes that change project files may Load projects if you need to make code
projects fail silently the first time. fixes to files of these projects.
Lightweight mode does not make fixes
to projects that are not loaded.
Unit Test Discovery Tests discovered on deferred projects Rebuild the project to rediscover tests
do not run when a project is loaded and run selected tests again.
manually.
Live unit testing (LUT) In LSL mode, you may see that LUT is Load any test project to activate live
not activated. It is not activated unit testing for the solution.
because LUT needs one of the test
projects to get loaded.
Solution Explorer Search 1. Solution Explorer search in LSL mode Load the entire solution in non-LSL
does not search within the files and mode to get traditional Solution
there are no progression results (that is, Explorer search.
only files are shown under the search You can also use Visual Studio IDE
tree, but not classes, methods, etc.). search.
2. All files belonging to a project are
shown as a flat list instead of a tree
view. When files belong to a folder of a
project, we show the relative path of
the file, instead of just the file name on
the search view.
There are no context menus for the file
items in the search view.
Object Browser for C++ Projects Object Browser shows Load projects for which you want to see
assembly/WinMD references for only information in the Object browser.
loaded projects.
NOTE
Thanks to our partners, popular extensions including Resharper also work well with lightweight solution load.
We are excited about innovations to optimize solution load time performance for developers. Since this is a new
feature, we are actively looking at customer feedback, and addressing known issues. We look forward to hearing
your feedback. You can email Visual Studio solution load optimization team at lslsupport@microsoft.com
See Also
Visual Studio Performance Tips and Tricks
Visual Studio Performance Tips and Tricks
10/24/2017 • 6 min to read • Edit Online
Visual Studio performance recommendations are intended for low memory situations, which may occur in rare
cases. In these situations, you can optimize certain Visual Studio features that you may not be using. The following
tips are not intended as general recommendations.
NOTE
If you’re having difficulty using the product because of memory issues, let us know through the feedback tool.
TIP
You can often isolate performance issues by turning off extensions one at a time and rechecking performance.
See Also
Visual Studio IDE
Connected environment
10/18/2017 • 1 min to read • Edit Online
In this section
Signing in to Visual Studio Describes how and why to sign in to Visual Studio.
Work with multiple user accounts Describes how to associate multiple Microsoft accounts
and/or work or school accounts to enable access to resources
and services from all your accounts.
How to Unlock Visual Studio Describes how to unlock Visual Studio in various scenarios.
Notifications Describes how Visual Studio notifies you when Visual Studio
or components such as SDKs have an update available.
Whitelisting URLs in a private network Describes which URLs to whitelist for Visual Studio
functionality if you're in a private network that has a firewall.
Proxy authorization required error Describes which URLs to whitelist for Visual Studio
functionality when you're connected to the internet through a
proxy server.
See also
Visual Studio IDE
Install Visual Studio behind a firewall or proxy server
Sign in to Visual Studio
10/18/2017 • 2 min to read • Edit Online
You can personalize and optimize your development experience in Visual Studio if you set your Personalization
account by signing in to the IDE.
Unless you sign out, you're automatically signed in to Visual Studio whenever you start it, and any changes to
synchronized settings are automatically applied. To sign out, choose the down arrow next to your profile name in
the upper-right corner of the Visual Studio environment, choose the Account settings command, and then
choose the Sign out link. To sign in again, choose the Sign in command in the upper-right corner of the Visual
Studio environment.
See also
Connected environment
Work with multiple user accounts
10/18/2017 • 4 min to read • Edit Online
If you have multiple Microsoft accounts and/or work or school accounts, you can add them all to Visual Studio so
that you can access the resources from any account without having to sign in to it separately. Currently, Azure,
Application Insights, Team Foundation Server, and Office 365 services support the streamlined sign-in experience.
Additional services may become available as time goes by.
After you add multiple accounts on one machine, that set of accounts will roam with you if you sign in to Visual
Studio on another machine. It is important to note that, although the account names roam, the credentials do not.
Therefore, you will be prompted to enter credentials for those other accounts the first time you attempt to use their
resources on the new machine.
This walkthrough shows how to add multiple accounts to Visual Studio, and how to see that the resources
accessible from those accounts are reflected in places such as the Add Connected Service dialog, Server
Explorer, and Team Explorer.
The first time you use Visual Studio on any specific device, the dialog will only show the subscriptions registered
under the ID that you signed in to the IDE with. You can access resources for any of your other accounts directly
from Server Explorer by right-clicking on the Azure node and choosing Manage and Filter Subscriptions and
adding your accounts from the account picker control. You can then choose another account, if desired, by clicking
the down arrow and choosing from the list of accounts. After choosing the account, you can choose which
subscriptions under that account you want to display in Server Explorer.
The next time you open Server Explorer, the resources for that subscription(s) are displayed.
Access your Azure account via Add Connected Service dialog
1. Create a Universal App project in C#.
2. Choose the project node in Solution Explorer and then choose Add, Connected Service. The Add
Connected Service wizard appears and shows you the list of services in the Azure account that is
associated with your Visual Studio login ID. Note that you do not have to sign in separately to Azure.
However, you do need to sign in to the other accounts the first time you attempt to access their resources
from a given computer.
WARNING
If this is the first time you are creating a Store app in Visual Studio on a specific computer, you will be prompted to
enable your device for development mode by going to Settings | Updates and Security | For Developers on your
computer. For more information, see Enable Your Device for Development.
Follow the prompts to enter the new account credentials. The following illustration shows the Account Manager
after a user has added his Contoso.com work account.
See also
Connected environment
How to: unlock Visual Studio
10/19/2017 • 2 min to read • Edit Online
You can evaluate Visual Studio for free up to 30 days. Signing into the IDE extends the trial period to 90 days. To
continue using Visual Studio, unlock the IDE by either:
using an online subscription
entering a product key
IMPORTANT
Visual Studio automatically looks for associated online subscriptions when you connect to a Visual Studio Team Services
account from the Team Explorer tool window. When you connect to a Visual Studio Team Services account, you can sign in
using both Microsoft and work or school accounts. If an online subscription exists for that user account, Visual Studio will
automatically unlock the IDE for you.
TIP
Pre-release versions of Visual Studio do not have product keys. You must sign in to the IDE to use pre-release versions.
This message indicates that while your subscription may still be valid, the license token Visual Studio uses to keep
your subscription up to date hasn't been refreshed and has gone stale due to one of the following reasons:
You have not used Visual Studio or have had no internet connection for an extended period of time.
You signed out of Visual Studio.
Before the license token goes stale, Visual Studio first shows a warning message asking you to reenter your
credentials.
If you do not reenter your credentials, the token starts to go stale and the Account Settings dialog tells you how
many days you have left before your token will fully expire. After your token expires, you will need to reenter your
credentials for this account or license with another method above before you can continue using Visual Studio.
IMPORTANT
If you are using Visual Studio for extended periods in environments with limited or no internet access, you should use a
product key to unlock Visual Studio in order to avoid interruption.
See also
Signing in to Visual Studio
Connected environment
Visual Studio notifications
10/18/2017 • 1 min to read • Edit Online
Visual Studio has a notification system that alerts you to various events, such as the following:
An update is available for Visual Studio or a component in Visual Studio.
An environment event that you might be interested in occurred.
Visual Studio notifies you when an update is available for Visual Studio itself or for any of the components that
have been installed. It also provides notifications about certain kinds of events that occur in the Visual Studio
environment. The notification icon is a flag in the upper right of the Visual Studio title bar; when the icon is red, it
means that there is a problem with your license. When it's yellow there is a Visual Studio Product Update available
for you to install. When it is "normal" or black you'll see messages that are informational or optional, such as
crashes for which you might want to find a workaround. You can click on the icon to open the Notifications Hub
and choose which ones to act on. You can choose to do a one-time dismiss on a notification, or always ignore a
notification (by hovering over it) and Visual Studio will never show you that message again.
If you choose to always ignore a notification, Visual Studio will stop showing it. You can reset the list of ignored
notifications in the Notifications, Environment, Options Dialog Box.
See also
Connected environment
Visual Studio IDE
Whitelisting URLs in a private network
10/18/2017 • 1 min to read • Edit Online
If you are using Visual Studio in a private network that uses a security appliance such as a firewall, Visual Studio
might not be able to connect to some network resources. These resources include Visual Studio Team Services
(VSTS) for sign-in and licensing, NuGet, and Azure services. If Visual Studio fails to connect to one of these
resources, you'll see the following error message:
The underlying connection was closed: An unexpected error occurred on send
Visual Studio uses Transport Layer Security (TLS) 1.2 protocol to connect to network resources. Security appliances
on some private networks block certain server connections when Visual Studio uses TLS 1.2. To fix the error, enable
connections for the following URLs:
https://management.core.windows.net
https://app.vssps.visualstudio.com
https://login.microsoftonline.com
https://login.live.com
https://go.microsoft.com
https://graph.windows.net
https://app.vsspsext.visualstudio.com
*.azurewebsites.net (for Azure connections)
*.nuget.org (for NuGet connections)
*.visualstudio.com
cdn.vsassets.io (hosts content delivery network, or CDN, content)
*.gallerycdn.vsassets.io (hosts VSTS extensions)
static2.sharepointonline.com (hosts resources that Visual Studio uses in the office fabric UI kit, such as fonts)
NOTE
Privately owned NuGet server URLs may not be included in the list above. You can check the NuGet servers you are using by
opening up %APPData%\Nuget\NuGet.Config.
See also
Proxy authorization required error
Connected environment
Install Visual Studio behind a firewall or proxy server
Proxy Authorization Required
10/18/2017 • 1 min to read • Edit Online
This error generally occurs when users are connected to the internet through a proxy server, and the proxy server
blocks the calls that Visual Studio makes to some network resources.
You must insert the correct proxy address for your network in
proxyaddress="<http://<yourproxy:port#> .
OR
You can also follow the instructions in this post to add code that will allow you to use the proxy.
See also
Connected environment
Solutions and Projects in Visual Studio
10/18/2017 • 2 min to read • Edit Online
When you create an app, website, plug-in, etc. in Visual Studio, you start with a project. In a logical sense, a project
contains of all the source code files, icons, images, data files and anything else that will be compiled into an
executable program or web site, or else is needed in order to perform the compilation. A project also contains all
the compiler settings and other configuration files that might be needed by various services or components that
your program will communicate with.
NOTE
You don't have to use solutions or projects if you don't want to. You can simply open the files into Visual Studio and start
editing your code. See Develop code in Visual Studio without projects or solutions for more information.
A project file (.vbproj, .csproj, .vcxproj) is an XML file that defines a virtual folder hierarchy along with paths to all
the items in the project. It also contains the build settings. To see the contents of a project file, you can select the
project name in Solution Explorer, then choose Unload Project from the context (right-click) menu. Then, open
the context menu again and choose Edit <projectname>.
In Visual Studio, the project file is used by Solution Explorer to display the project contents and settings. When you
compile your project, the MSBuild engine consumes the project file to create the executable. You can also
customize projects to produce other kinds of output.
A project is contained, in a logical sense and in the file system, within a solution, which may contain one or more
related projects, along with build information, Visual Studio window settings, and any miscellaneous files that
aren't associated with a particular project. A solution is described by a text file (.sln) with its own unique format; it
is generally not intended to be edited by hand.
A solution has an associated .suo file that stores settings, preferences and configuration information for each user
that has worked on the project.
The following diagram shows the relationship between projects and solutions, and the items they logically contain.
In This Section
Creating solutions and projects
Adding and removing project items
Managing project and solution properties
Managing references in a project
Application properties
Managing assembly and manifest signing
How to: specify an application Iicon (Visual Basic, C#)
Targeting a specific .NET Framework version
Creating project and item templates
See Also
Visual Studio IDE
Create solutions and projects
10/18/2017 • 6 min to read • Edit Online
Projects are logical containers in Visual Studio that hold the items needed to build your app, such as source code
files, bitmaps, icons, and component and service references. When you create a new project, Visual Studio creates
a solution to contain the projects. You can then add new or existing projects to the solution if you want. Solutions
can also contain files not connected to any specific project.
You can view your solutions and projects in a tool window called Solution Explorer. The following screenshot
shows an example solution in Solution Explorer (BikeSharing.Xamarin-UWP) that contains two projects:
BikeSharing.Clients.Core and BikeSharing.Clients.Windows. Each project contains multiple files, folders, and
references. The project name in bold is the startup project; that is, the project that starts when you run the app. You
can specify which project is the startup project.
While you can construct a project yourself by adding the necessary files to it, Visual Studio offers a selection of
project templates to give you a head start. Creating a new project from a template gives you a project with the
essentials for that project type, and you can rename the files or add new or existing code and other resources to it
as needed.
That being said, solutions and projects are not required to develop apps in Visual Studio. You can also just open
code that you have cloned from Git or downloaded elsewhere. For more information, see Develop code in Visual
Studio without projects or solutions.
NOTE
The descriptions in this topic are based on the Visual Studio Community edition. The dialog boxes and menu commands you
see might differ from those described here, depending on your settings or Visual Studio edition. To change your settings,
choose Tools, Import and Export Settings. For more information, see Personalize the Visual Studio IDE.
In the New Project dialog box, available project templates appear in a list under the Templates category.
Templates are organized by programming language and project type, such as Visual C#, JavaScript, and
Azure Data Lake.
NOTE
The list of available languages and project templates that appears depends on the version of Visual Studio you are
running and the workloads that are installed. To learn about how to install additional workloads, see Modify Visual
Studio 2017 by adding or removing workloads and components.
2. Show the list of templates for the programming language you want to use by choosing the triangle next to
the language name, and then choose a project type. The following example shows the project templates
available for Visual C# web projects.
3. Enter a name for the new project in the Name box. You can choose to save the project in the default
location on your system, or choose the Browse button to find another location.
You can also optionally choose to change the solution name, or add the new project to a Git repository by
choosing Add to Source Control.
4. Choose the OK button to create the solution and project.
5. If you want to add an additional project to a solution, choose the solution node in Solution Explorer, and
then on the menu, choose Project, Add New Item.
NOTE
This option works best for a relatively simple collections of files. Currently, only Visual C++, Apache Cordova, Visual Basic,
and Visual C# project types are supported.
You must have .NET Framework 3.5 installed on your system to access .NET Framework versions earlier than .NET
Framework 4.
NOTE
The .suo file is a hidden file that is not displayed under the default File Explorer settings. To show hidden files, on the View
menu in File Explorer, select the Hidden Items checkbox.
See Also
Solutions and Projects
Microsoft's open source repositories on GitHub
Visual Studio Samples
Developer code samples
Adding and Removing Project Items
10/18/2017 • 1 min to read • Edit Online
You can add or remove projects and project items by right-clicking on the project or solution node in Solution
Explorer, and choosing Add or Remove. Removing a project from a solution, or an item from a project, does not
delete it from disk or source control unless you select the option to delete it permanently.
See Also
Solutions and Projects
Managing Project and Solution Properties
Managing Project and Solution Properties
10/18/2017 • 1 min to read • Edit Online
Projects have properties that govern many aspects of compilation, debugging, testing and deploying. Some
properties are common among all project types, and some are unique to specific languages or platforms. You
access project properties by right-clicking the project node in Solution Explorer and choosing Properties, or by
typing properties into the QuickLaunch search box in the menu bar.
.NET projects might also have a properties node in the project tree itself.
TIP
Solutions have a few properties, and so do project items; these properties are accessed in the Properties Window, not
Project Designer.
Project Properties
Project Properties are organized into groups and each group has its own property page, and the pages might be
different for different languages and project types.
C#, Visual Basic and F# projects
In C#, Visual Basic and F# projects, properties are exposed in the Project Designer. The following illustration
shows the Build property page for a WPF project in C#:
For information about each of the property pages in Project Designer, see Project Properties Reference.
C++ and JavaScript projects
C++ and JavaScript projects have a different user interface for managing project properties. This illustration
shows a C++ project property page (JavaScript pages are similar):
For information about C++ project properties, see Working with Project Properties. For more information about
JavaScript properties, see Property Pages, JavaScript.
Solution Properties
To access properties on the solution, right click the solution node in Solution Explorer and choose Properties. In
the dialog, you can set project configurations for Debug or Release builds, choose which projects should be the
startup project when F5 is pressed, and set code analysis options.
See Also
Solutions and Projects in Visual Studio
Managing references in a project
10/18/2017 • 6 min to read • Edit Online
Before you write code against an external component or connected service, your project must first contain a
reference to it. A reference is essentially an entry in a project file that contains the information that Visual Studio
needs to locate the component or the service.
To add a reference, right click on the References node in Solution Explorer and choose Add Reference. For more
information, see How to: Add or Remove References By Using the Reference Manager.
NOTE
One way to find out whether an Extension SDK has dependencies on other Extension SDKs is to restart Visual
Studio, create a new C# Windows Store project, right-click on the project and choose Add Reference, go to the
Windows tab, go to the Extensions sub-tab, select the Extension SDK and look at the right pane in the Reference
Manager. If it has dependencies, they will be listed there.
IMPORTANT
If your project is targeting Windows 10, and the Extension SDK installed in the previous step has a dependency on
the Microsoft Visual C++ Runtime Package, the version of Microsoft Visual C++ Runtime Package that is
compatible with Windows 10 is v14.0 and is installed with Visual Studio.
3. If the Extension SDK you installed in the previous step has dependencies on other Extension SDKs, go to the
site(s) of the vendor(s) who own the dependencies and install the versions of these dependencies that are
compatible with the version of the platform your project is targeting.
4. Restart Visual Studio and open your app.
5. Right-click on the References node in the project that caused the error and choose Add Reference
6. Click the Windows tab and then the Extensions sub-tab, then uncheck the checkboxes for the old
Extension SDKs and check the checkboxes for the new Extension SDKs. Click OK.
NOTE
All projects contain an implied reference to mscorlib. Visual Basic projects contain an implied reference to
Microsoft.VisualBasic .
All projects in Visual Studio contain an implied reference to System.Core , even if System.Core is removed from the list of
references.
Project-to-Project References
Project-to-project references are references to projects that contain assemblies; you create them by using the
Project tab. Visual Studio can find an assembly when given a path to the project.
When you have a project that produces an assembly, you should reference the project and not use a file reference
(see below). The advantage of a project-to-project reference is that it creates a dependency between the projects
in the build system. The dependent project will be built if it has changed since the last time the referencing project
was built. A file reference does not create a build dependency, so it is possible to build the referencing project
without building the dependent project, and the reference can become obsolete. (That is, the project can reference
a previously built version of the project.) This can result in several versions of a single DLL being required in the
bin directory, which is not possible. When this conflict occurs, you will see a message such as "Warning: the
dependency 'file' in project 'project' cannot be copied to the run directory because it would overwrite the
reference 'file.'". For more information, see Troubleshooting Broken References and How to: Create and Remove
Project Dependencies.
NOTE
A file reference instead of a project-to-project reference is created if the target version of the .NET Framework of one project
is version 4.5, and the target version of the other project is version 2, 3, 3.5, or 4.0.
File References
File references are direct references to assemblies outside the context of a Visual Studio project; you create them
by using the Browse tab of the Reference Manager. Use a file reference when you just have an assembly or
component and don't have the project that creates it as output.
See Also
Troubleshooting Broken References
How to: Add or Remove References By Using the Reference Manager
How to: Add or Remove References By Using the
Reference Manager
10/18/2017 • 13 min to read • Edit Online
You can use the Reference Manager dialog box to add and manage references to components that you,
Microsoft, or another company developed. If you're developing a Universal Windows app, your project
automatically references all of the correct Windows SDK DLLs. If you are developing a .NET application, your
project automatically references mscorlib.dll. Some .NET APIs are exposed in components that you have to add
manually. References to COM components or custom components have to be added manually.
Assemblies tab
The Assemblies tab lists all .NET Framework assemblies that are available for referencing. The Assemblies tab
doesn't list any assemblies from the global assembly cache (GAC) because assemblies in the GAC are part of the
run-time environment. If you deploy or copy an application that contains a reference to an assembly that's
registered in the GAC, the assembly won't be deployed or copied with the application, regardless of the Copy Local
setting. For more information, see Managing references in a project.
When you manually add a reference to any of the EnvDTE namespaces (EnvDTE, EnvDTE80, EnvDTE90, EnvDTE90a,
or EnvDTE100), set the Embed Interop Types property of the reference to False in the Properties window. Setting
this property to True can cause build issues because of certain EnvDTE properties that can't be embedded.
All desktop projects contain an implicit reference to mscorlib. Visual Basic projects contain an implicit reference to
Microsoft.VisualBasic. In Visual Studio 2012, all projects contain an implicit reference to System.Core, even if it's
removed from the list of references.
If a project type doesn't support Assemblies, the tab won't appear in the Reference Manager dialog box.
The Assemblies tab consists of two sub-tabs:
1. Framework lists all assemblies that constitute the targeted Framework.
Advertised assemblies are in the Full Framework and enumerated in the Framework list when your
project targets a Profile of the targeted Framework. Advertised assemblies are grey to differentiate
them from the assemblies that exist in the targeted Framework profile of the project. For example, if a
project targets .NET Framework 4 Client, the Framework list shows advertised assemblies from .NET
Framework 4. When a user adds an advertised assembly, the user is notified that, after the
Reference Manager dialog box is closed, the project will be retargeted to the .NET Framework 4 and
the advertised assembly will be added.
Projects for Windows 8.x Store apps contain references to all of the assemblies in the targeted .NET
for Windows 8.x Store apps by default on project creation. In managed projects, a read-only node
under the References folder in Solution Explorer indicates the reference to the entire Framework.
Accordingly, the Framework tab won't enumerate any of the assemblies from the Framework and
instead display the following message: "All of the Framework assemblies are already referenced.
Please use the Object Browser to explore the references in the Framework." For desktop projects, the
Framework tab enumerates assemblies from the targeted Framework, and the user must add the
references that the application requires.
2. Extensions lists all assemblies that external vendors of components and controls have developed to extend
the targeted Framework. Depending on the purpose of the user application, it might need these assemblies.
Extensions is populated by enumerating the assemblies that are registered in the following locations:
32-bit machine:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
64-bit machine:
HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\[Target Framework Identifier]\v[Target Framework
Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\[Target Framework Identifier]\v[Target
Framework Version]\AssemblyFoldersEx\[UserComponentName]\@default=[Disk location of assemblies]
And older versions of the [Target Framework Identifier]
For example, if a project targets the .NET Framework 4 on a 32-bit machine, Extensions will
enumerate assemblies that are registered under
\Microsoft\.NETFramework\v4.0\AssemblyFoldersEx\,
\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\,
\Microsoft\.NETFramework\v3.0\AssemblyFoldersEx\, and
\Microsoft\.NETFramework\v2.0\AssemblyFoldersEx\.
Some components in the list may not be shown, depending on the .NET Framework version of your project.
This can occur under the following conditions:
A component that uses a recent version of the .NET Framework is incompatible with a project that targets an
earlier version of the .NET Framework.
For information about how to change the target .NET Framework version for a project, see How to: Target a
Version of the .NET Framework.
A component that uses .NET Framework 4 is incompatible with a project that targets the .NET Framework
4.5.
When you create a new application, some projects target the .NET Framework 4.5 by default.
You should avoid adding file references to outputs of another project in the same solution, because doing
this may cause compilation errors. Instead, use the Projects tab of the Add Reference dialog box to create
project-to-project references. This makes team development easier by enabling better management of the
class libraries you create in your projects. For more information, see Troubleshooting Broken References.
NOTE
In Visual Studio 2015 or later, a file reference instead of a project reference is created if the target version of the .NET
Framework of one project is version 4.5 or later, and the target version of the other project is version 2, 3, 3.5, or 4.0.
COM tab
The COM tab lists all COM components that are available for referencing. If you want to add a reference to a
registered COM DLL that contains an internal manifest, unregister the DLL first. Otherwise, Visual Studio adds the
assembly reference as an ActiveX Control instead of as a native DLL.
If a project type doesn't support COM, the tab won't appear in the Reference Manager dialog box.
Solution tab
The Solution tab lists all compatible projects within the current solution, in the Projects sub-tab.
A project can reference another project that targets a different version of the .NET Framework. For example, you
could create a project that targets the .NET Framework 4 but that references an assembly that's been built for the
.NET Framework 2. However, the .NET Framework 2 project can't reference a .NET Framework 4 project. For more
information, see Targeting a Specific .NET Framework Version.
A project that targets the .NET Framework 4 is incompatible with a project that targets the .NET Framework 4 Client
Profile.
In Visual Studio 2012, a file reference instead of a project reference is created if one project targets the .NET
Framework 4 and another project targets an earlier version.
A project that targets the .NET for Windows 8.x Store apps can't add a project reference to a project that targets the
.NET Framework and vice versa.
Windows tab
The Windows tab lists all SDKs that are specific to platforms on which Windows operating systems run.
You can generate a WinMD file in Visual Studio in two ways:
Windows 8.x Store app managed projects: Windows 8.x Store app projects can output WinMD binaries
by setting Project Properties | Output Type = WinMD File. The WinMD filename must be the superset
namespace of all the namespaces that exist within it. For example, if a project consists of namespaces A.B
and A.B.C, the possible names for its outputted WinMD are A.winmd and A.B.winmd. If a user enters a
Project Properties | Assembly Name or Project Properties | Namespace value that's disjoint from the set of
namespaces in the project or there is no superset namespace within a project, a build warning is generated:
'A.winmd' isn't a valid .winmd file name for this assembly. All types within a Windows Metadata file must
exist in a sub namespace of the file name. Types that don't exist in a sub namespace of the file name won't
be able to be located at runtime. In this assembly, the smallest common namespace is 'CSWSClassLibrary1'.
A desktop Visual Basic or Visual C# project can only consume WinMDs that are generated by using the
Windows 8 SDKs, which are known as first-party WinMDs, and can't generate WinMDs.
Windows 8.x Store app native projects: A native WinMD file consists of only metadata. Its
implementation exists in a separate DLL file. One can produce native binaries by choosing the Windows
Runtime Component project template in the New Project dialog box or by starting from a blank project
and modifying the project properties to generate a WinMD file. If the project consists of disjoint
namespaces, a build error will tell the user to combine their namespaces or run the MSMerge tool.
The Windows tab consists of two subgroups.
Core Subgroup
The Core subgroup lists all of the WinMDs (for Windows Runtime elements) in the SDK for the targeted version of
Windows.
Windows 8.x Store app projects contain references to all of the WinMDs in the Windows 8 SDK by default on
project creation. In managed projects, a read-only node under the References folder in Solution Explorer
indicates the reference to the entire Windows 8 SDK. Accordingly, the Core subgroup in the Reference Manager
won't enumerate any of the assemblies from the Windows 8 SDK and instead displays a message: "The Windows
SDK is already referenced. Please use the Object Browser to explore the references in the Windows SDK."
In the desktop projects, the Core subgroup doesn't appear by default. You can add the Windows Runtime by
opening the shortcut menu for the project node, choosing Unload Project, adding the following snippet, and re-
opening the project (on the project node, choose Reload Project). When you invoke the Reference Manager
dialog box, the Core subgroup appears.
<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>
Make sure to select the Windows check box on this subgroup. You should then be able to use Windows Runtime
elements. However, you'll also want to add System.Runtime, in which the Windows Runtime defines some
standard classes and interfaces, such as IEnumerable, that are used throughout the Windows Runtime libraries. For
information about how to add System.Runtime, see Managed desktop apps and Windows Runtime.
Extensions Subgroup
Extensions lists the user SDKs that extend the targeted Windows platform. This tab appears for Windows 8.x Store
app projects only. Desktop projects won't show this tab because they can consume only first-party .winmd files.
An SDK is a collection of files that Visual Studio treats as a single component. In the Extensions tab, SDKs that apply
to the project from which the Reference Manager dialog box was invoked are listed as single entries. When
added to a project, all of the SDK content is consumed by Visual Studio such that the user doesn't need to take any
further actions to leverage the SDK contents in IntelliSense, toolbox, designers, Object Browser, build, deployment,
debugging, and packaging. For information about how to display your SDK in the Extensions tab, see Creating a
Software Development Kit.
NOTE
If a project references an SDK that depends on another SDK, Visual Studio won't consume the second SDK unless the user
manually adds a reference to the second SDK. When a user chooses an SDK on the Extensions tab, the Reference
Manager dialog box helps the user identify SDK dependencies by listing not only the name and version of the SDK but also
the name of any SDK dependencies in the details pane. If a user doesn't notice the dependencies and only adds that SDK,
MSBuild will prompt the user to add the dependencies.
If a project type doesn't support Extensions, the tab doesn't appear in the Reference Manager dialog box.
Browse button
You can use the Browse button to browse for a component in the file system.
A project can reference a component that targets a different version of the .NET Framework. For example, you
could create an application that targets the .NET Framework 4 Client Profile, which references a component that
targets the .NET Framework 2. For more information, see Targeting a Specific .NET Framework Version.
You should avoid adding file references to outputs of another project in the same solution, because this tactic may
cause compilation errors. Instead, use the Solution tab of the Reference Manager dialog box to create project-
to-project references. This tactic makes team development easier by enabling better management of the class
libraries that you create in your projects. For more information, see Troubleshooting Broken References.
You can't browse to an SDK and add it to your project. You can only browse to a file (for example, an assembly or
.winmd) and add it to your project.
When doing a file reference to a WinMD, the expected layout is that the FileName.winmd, FileName.dll, and
FileName.pri files are all placed alongside each other. If you reference a WinMD in the following scenarios, an
incomplete set of files will be copied into the project output directory and, consequently, build and runtime failures
will occur.
Native component: a native project will create one WinMD for each disjoint set of namespaces and one
DLL that consists of the implementation. The WinMDs will have disparate names. When referencing this
native component file, MSBuild won't recognize that the dissimilarly named WinMDs make one component.
Consequently, only the identically named FileName.dll and FileName.winmd will be copied, and runtime
errors will occur. To work around this issue, create an Extension SDK. For more information, see Creating a
Software Development Kit.
Consuming controls: at a minimum, a XAML control consists of a FileName.winmd, FileName.dll,
FileName.pri, XamlName.xaml, and an ImageName.jpg. When the project is built, the resource files that are
associated with the file reference won't get copied into the project's output directory, and only
FileName.winmd, FileName.dll and FileName.pri will be copied. A build error is logged to inform the user
that the resources XamlName.xaml and ImageName.jpg are missing. To succeed, the user will have to
manually copy these resource files into the project output directory for build and debugging/runtime. To
work around this issue, either create an Extension SDK by following the steps in Creating a Software
Development Kit or edit the project file to add the following property:
<PropertyGroup>
<GenerateLibraryOutput>True</GenerateLibraryOutput>
</PropertyGroup>
NOTE
If you add the property, the build might run slower.
Recent
Assemblies, COM, Windows, and Browse each support a Recent tab, which enumerates the list of components that
were recently added to projects.
Search
The search bar in the Reference Manager dialog box operates over the tab that's in focus. For example, if a user
types "System" in the search bar while the Solution tab is in focus, the search won't return any results unless the
solution consists of a project name that contains "System".
See Also
Managing references in a project
Adding References Using NuGet Versus an Extension
SDK
10/18/2017 • 6 min to read • Edit Online
You can provide a package for consumption within Visual Studio projects by using either the NuGet extension to
Visual Studio or a software development kit (SDK). By describing the similarities and differences between the two
mechanisms, this topic can help you choose the best one for your task.
NuGet is an open-source, package-management system that simplifies the process of incorporating libraries
into a project solution. For more information, see the NuGet documentation.
An SDK is a collection of files that Visual Studio treats as a single reference item. The Reference Manager
dialog box lists all SDKs that are relevant to the project that's open when you display that dialog box. When
you add an SDK to a project, you can access all of the contents of that SDK through IntelliSense, the
Toolbox, designers, the Object Browser, MSBuild, deployment, debugging, and packaging. For more
information about SDKs, see Creating a Software Development Kit.
The mechanism N Because you reference Y You can check out the
supports a clean an SDK, you must solution, and Visual
developer machine. check in your solution Studio immediately
(That is, no and the SDK recognizes and acts
installation is separately. You can on the files.
required, and simple check in the SDK from
retrieval from source the two non-registry
code control will default locations from
work.) which MSBuild
iterates SDKs (for
details, see Creating a
Software
Development Kit). As
an alternative, if a
custom location
consists of the SDKs,
you can specify the
following code in the
project file:
<PropertyGroup>
<SDKReferenceDirectoryRoot>C:\MySDKs</SDKReferenceDirectoryRoot>
</PropertyGroup>
See Also
Managing references in a project
How to: Add or Remove Imported Namespaces
(Visual Basic)
10/18/2017 • 2 min to read • Edit Online
Importing a namespace allows you to use elements from that namespace in your code without fully qualifying the
element. For example, if you want to access the Create method in the System.Messaging.MessageQueue class, you
can import the System.Messaging namespace and just refer to the element you need in code as
MessageQueue.Create .
Imported namespaces are managed on the References page of the Project Designer. The imports you specify in
this dialog box are passed directly to the compiler ( /imports ) and apply to all files in your project. Use the Imports
statement to use a namespace in a single source code file.
To add an imported namespace
1. In Solution Explorer, double-click the My Project node for the project.
2. In the Project Designer, click the References tab.
3. In the Imported Namespaces list, select the check box for the namespace that you wish to add.
NOTE
In order to be imported, the namespace must be in a referenced component. If the namespace does not appear in the
list, you will need to add a reference to the component that contains it. For more information, see Managing
references in a project.
User Imports
User imports allow you to import a specific class within a namespace rather than the entire namespace. For
example, your application might have an import for the Systems.Diagnostics namespace, but the only class within
that namespace that you are interested in is the Debug class. You can define System.Diagnostics.Debug as a user
import, and then remove the import for System.Diagnostics .
If you later change you mind and decide that was really the EventLog class that you needed, you could enter
System.Diagnostics.EventLog as a user import and overwrite System.Diagnostics.Debug using the update
functionality.
To add a user import
1. In Solution Explorer, double-click the My Project node for the project.
2. In the Project Designer, click the References tab.
3. In the text box below the Imported Namespaces list, enter the full name for the namespace you wish to
import, including the root namespace.
4. Click the Add user import button to add the namespace to the Imported Namespaces list.
NOTE
The Add user import button will be disabled if the namespace matches one already in the list; you cannot add an
import twice.
See Also
Managing references in a project
Troubleshoot broken references
10/18/2017 • 3 min to read • Edit Online
If your application attempts to use a broken reference, an exception error is generated. The inability to find the
referenced component is the primary trigger for the error, but there are several situations in which a reference can
be considered broken. These instances are shown in the following list:
The project's reference path is incorrect or incomplete.
The file being referenced has been deleted.
The file being referenced has been renamed.
The network connection or authentication has failed.
The reference is to a COM component that is not installed on the computer.
The following are remedies to these problems.
NOTE
Files in assemblies are referenced with absolute paths in the project file. Therefore, it is possible for users who work in a
multideveloper environment to be missing a referenced assembly in their local environment. To avoid these errors, it is
better in these cases to add project-to-project references. For more information, see Programming with Assemblies.
TIP
Project-to-project references do not have these problems. For this reason, use them instead of file references, if you can.
See also
References Page, Project Designer (Visual Basic)
Application Properties
10/18/2017 • 1 min to read • Edit Online
You can set general application properties for Visual Basic, C#, and F# applications, such as application type, startup
object, and assembly information, in the Application pane of the Project Designer.
The following tasks can be accomplished in the Application pane:
Specify assembly information
Specify a splash screen for an application
Specify application-level events
Change an assembly name
Change the namespace for an application
Change the application type
Change the Startup object for an application
Specify an application icon
Enable Windows XP visual styles
Specify instancing behavior for an application
Enable custom user authentication
Specify shutdown behavior for an application
The tasks available for your application depend on the development language being used.
In This Section
How to: Specify an Application Icon (Visual Basic, C#)
See Also
Application Page, Project Designer (Visual Basic)
Application Page, Project Designer (C#)
Publishing ClickOnce Applications
Securing ClickOnce Applications
Managing Debugging Properties
Managing Compilation Properties
Managing Application Resources (.NET)
Managing Application Settings (.NET)
Managing Application Resources (.NET)
10/18/2017 • 1 min to read • Edit Online
Resource files are files that are part of an application but are not compiled, for example icon files or audio files.
Since these files are not part of the compilation process, you can change them without having to recompile your
binaries. If you are planning to localize your application, you should use resource files for all the strings and other
resources that need to be changed when you localize your application.
For more information about resources in .NET desktop apps, see Resources in Desktop Apps. For more information
about resources in C++ desktop apps, see Working with Resource Files.
Windows Store apps use a different resource model from desktop apps. For information about resources in
Windows Store apps, see Defining Application Resources on the Windows Dev Center website.
Application settings enable you to store application information dynamically. Settings allow you to store
information on the client computer that should not be included in the application code (for example a connection
string), user preferences and other information you need at runtime.
Application settings replace the dynamic properties used in earlier versions of Visual Studio.
Each application setting must have a unique name. The name can be any combination of letters, numbers, or an
underscore that does not start with a number, and it cannot contain spaces. The name can be changed through the
Name property.
Application settings can be stored as any data type that can be serialized to XML or has a TypeConverter that
implements ToString / FromString . The most common types are String , Integer , and Boolean , but you can also
store values as Color, Object, or as a connection string.
Application settings also contain a value. The value is set with the Value property and must match the data type of
the setting.
In addition, application settings can be bound to a property of a form or control at design time.
There are two types of application settings, based on scope:
Application-scoped settings can be used for information such as a URL for a Web service or a database
connection string. These values are associated with the application. Therefore, users cannot change them at
run time.
User-scoped settings can be used for information such as persisting the last position of a form or a font
preference. Users can change these values at run time.
You can change the type of a setting by using the Scope property.
The project system stores application settings in two XML files: an app.config file, which is created at design
time when you create the first application setting; and a user.config file, which is created at run time when
the user who runs the application changes the value of any user setting. Notice that changes in user settings
are not written to disk unless the application specifically calls a method to do this.
NOTE
Because there is no configuration file model for class libraries, application settings do not apply for Class Library projects. The
exception is a Visual Studio Tools for Office DLL project, which can have a configuration file.
The Settings Designer first searches for the Settings.settings file that the project system creates; this is the default
file that the Project Designer displays in the Settings tab. Settings.settings is located in the My Project folder for
Visual Basic projects and in the Properties folder for Visual C# projects. The Project Designer then searches for
other settings files in the project's root folder. Therefore, you should put your custom settings file there. If you add
a .settings file elsewhere in your project, the Project Designer will not be able to locate it.
Properties.Settings.Default.FirstUserSetting = "abc";
You must also explicitly call the Save method of this wrapper class in order to persist the user settings. You usually
do this in the Closing event handler of the main form. The following Visual C# example shows a call to the Save
method.
Properties.Settings.Default.Save();
For general information about accessing application settings through the Settings class, see Application Settings
Overview. For information about iterating through the settings, see this forum post.
See Also
Accessing Application Settings
Managing Assembly and Manifest Signing
10/18/2017 • 2 min to read • Edit Online
Strong-name signing gives a software component a globally unique identity. Strong names are used to guarantee
that the assembly cannot be spoofed by someone else, and to ensure that component dependencies and
configuration statements map to the correct component and component version.
A strong name consists of the assembly's identity (simple text name, version number, and culture information),
plus a public key token and a digital signature.
For information about signing assemblies in Visual Basic and C# projects, see Creating and Using Strong-Named
Assemblies.
For information about signing assemblies in Visual C++ projects, see Strong Name Assemblies (Assembly Signing)
(C++/CLI).
NOTE
Strong-name signing does not protect against reverse-engineering of the assembly. To protect against reverse-engineering,
see Dotfuscator Community Edition (CE).
WARNING
You should always protect your key file with a password to prevent someone else from using it. You can also secure your
keys by using providers or certificate stores.
You can also point to a key you have already created. For more information about creating keys, see How to: Create
a Public-Private Key Pair.
If you have access only to a public key, you can use delay signing to defer assigning the key. You enable delay
signing by selecting the Delay sign only check box. A delay-signed project won't run, and you can't debug it.
However, you can skip verification during development by using the Sn.exe (Strong Name Tool) with the -Vr
option.
For information about signing manifests, see How to: Sign Application and Deployment Manifests.
See Also
Strong-Named Assemblies
Strong Name Assemblies (Assembly Signing) (C++/CLI)
How to: Sign Application and Deployment Manifests
10/18/2017 • 4 min to read • Edit Online
If you want to publish an application by using ClickOnce deployment, the application and deployment manifests
must be signed with a public/private key pair and signed using Authenticode technology. You can sign the
manifests by using a certificate from the Windows certificate store or a key file.
For more information about ClickOnce deployment, see ClickOnce Security and Deployment.
Signing the ClickOnce manifests is optional for .exe-based applications. For more information, see the "Generating
Unsigned Manifests" section of this document.
For information about creating key files, see How to: Create a Public-Private Key Pair.
NOTE
Visual Studio supports only Personal Information Exchange (PFX) key files that have the .pfx extension. However, you can
select other types of certificates from the current user's Windows certificate store by clicking Select from Store on the
Signing page of project properties.
TIP
If you click Click here to view certificate properties, the Certificate Details dialog box appears. This dialog box
includes detailed information about the certificate, and includes additional options. You can click certificates to view
additional Help information.
3. Select the certificate that you want to use to sign the manifests.
4. Additionally, you can specify the address of a timestamp server in the Timestamp server URL text box. This
is a server that provides a timestamp specifying when the manifest was signed.
To sign application and deployment manifests using an existing key file
1. On the Signing page, select the Sign the ClickOnce manifests check box.
2. Click the Select from File button.
The Select File dialog box appears.
3. In the Select File dialog box, browse to the location of the key file (.pfx) that you want to use, and then click
Open.
NOTE
This option supports only files that have the .pfx extension. If you have a key file or certificate in another format, store
it in the Windows certificate store and select the certificate is described in the previous procedure. The selected
certificate's purpose should include code signing.
The Enter password to open file dialog box appears. (If the .pfx file is already stored in your Windows
certificate store, or is not password protected, you will not be prompted to enter a password.)
4. Enter the password to access the key file, and press ENTER.
To sign application and deployment manifests using a test certificate
1. On the Signing page, select the Sign the ClickOnce manifests check box.
2. To create a new certificate for testing, click the Create Test Certificate button.
3. In the Create Test Certificate dialog box, enter a password to help secure your test certificate.
IMPORTANT
Unsigned manifests can simplify development and testing of your application. However, unsigned manifests introduce
substantial security risks in a production environment. Only consider using unsigned manifests if your ClickOnce application
runs on computers within an intranet that is completely isolated from the internet or other sources of malicious code.
By default, ClickOnce automatically generates signed manifests unless one or more files are specifically excluded
from the generated hash. In other words, publishing the application results in signed manifests if all files are
included in the hash, even when the Sign the ClickOnce manifests check box is cleared.
To generate unsigned manifests and include all files in the generated hash
1. To generate unsigned manifests that include all files in the hash, you must first publish the application
together with signed manifests. Therefore, first sign the ClickOnce manifests by following one of the
previous procedures, and then publish the application.
2. On the Signing page, clear the Sign the ClickOnce manifests check box.
3. Reset the publish version so that only one version of your application is available. By default, Visual Studio
automatically increments the revision number of the publish version every time that you publish an
application. For more information, see How to: Set the ClickOnce Publish Version.
4. Publish the application.
To generate unsigned manifests and exclude one or more files from the generated hash
1. On the Signing page, clear the Sign the ClickOnce manifests check box.
2. Open the Application Files dialog box and set the Hash to Exclude for the files that you want to exclude
from the generated hash.
NOTE
Excluding a file from the hash configures ClickOnce to disable automatic signing of the manifests, so you do not need
to first publish with signed manifests as shown in the previous procedure.
3. Publish the application.
See Also
Strong-Named Assemblies
How to: Create a Public-Private Key Pair
Signing Page, Project Designer
ClickOnce Security and Deployment
How to: Specify an Application Icon (Visual Basic, C#)
10/18/2017 • 1 min to read • Edit Online
The Icon property for a project specifies the icon file (.ico) that will be displayed for the compiled application in
File Explorer and in the Windows taskbar.
The Icon property can be accessed in the Application pane of the Project Designer; it contains a list of icons
that have been added to a project either as resources or as content files.
NOTE
After you set the icon property for an application, you might also set the Icon property of each Window or Form in the
application. For information about window icons for Windows Presentation Foundation (WPF) standalone applications, see
Icon property.
See Also
Application Page, Project Designer (Visual Basic)
Application Page, Project Designer (C#)
Managing Application Properties
How to: Add or Remove Resources
Targeting a Specific .NET Framework Version
10/18/2017 • 1 min to read • Edit Online
In Visual Studio, you can specify the version or profile of the .NET Framework that you want your project to target.
For an application to run on another computer, the Framework version that the application targets must be
compatible with the Framework version that is installed on the computer.
This section contains topics that describe how to target specific versions of the .NET Framework in your projects.
In This Section
Visual Studio Multi-Targeting Overview
Provides an overview of the multi-targeting features in Visual Studio.
How to: Target a Version of the .NET Framework
Details how to specify a particular .NET Framework for your Visual Basic, Visual C# or Visual F# project.
Related Sections
.NET Framework Multi-Targeting for ASP.NET Web Projects
Explains how to use this version of Visual Studio to develop Web applications that run under earlier versions of
the .NET Framework.
Application Page, Project Designer (C#)
Describes the Target Framework control in the Project Designer for Visual C# projects.
Application Page, Project Designer (Visual Basic)
Describes the Target Framework control in the Project Designer for Visual Basic projects.
How to: Modify the Target Framework and Platform Toolset
Describes how to change settings for Visual C++ projects to target different versions of the .NET Framework and
to use different platform toolsets.
Visual Studio Multi-Targeting Overview
10/18/2017 • 4 min to read • Edit Online
In this version of Visual Studio, you can specify the version of the .NET Framework that is required for your
application. Therefore, if you want to use this version of Visual Studio to continue to develop a project that you
started in an earlier version, you do not have to change the framework target. You could also create a solution that
contains projects that target different versions of the framework. Framework targeting also helps guarantee that
the application uses only functionality that is available in the specified version of the framework.
TIP
You can also target applications for different platforms. For more information, see Multitargeting
NOTE
Framework targeting does not guarantee that your application will run correctly. You must test your application to make
sure it runs against the targeted version. You cannot target framework versions that are earlier than the .NET Framework
2.0.
Selecting a Target Framework Version
When you create a project, select the target .NET Framework version in the New Project dialog box. The list of
available project templates is filtered based on the selection. In an existing project, you can change the target .NET
Framework version in the project properties dialog box. For more information, see How to: Target a Version of the
.NET Framework.
NOTE
In Express editions of Visual Studio, you cannot set the target framework in the New Project dialog box.
NOTE
A .NET Framework client profile is a subset of the .NET Framework that provides a limited set of libraries and features. For
more information about client profiles, see .NET Framework Client Profile.
The Add Reference dialog box disables system assemblies that do not pertain to the target .NET Framework
version so that they cannot be added to a project inadvertently. (System assemblies are .dll files that are included
in a .NET Framework version.) References that belong to a framework version that is later than the targeted version
will not resolve, and controls that depend on such a reference cannot be added. If you want to enable such a
reference, reset the .NET Framework target of the project to one that includes the reference. For more information,
see How to: Target a Version of the .NET Framework.
For more information about assembly references, see Resolving Assemblies at Design Time.
Enabling LINQ
When you target the .NET Framework 3.5 or later, a reference to System.Core and a project-level import for
System.Linq (in Visual Basic only) are added automatically. If you want to use LINQ features, you must also turn
Option Infer on (in Visual Basic only). The reference and import are removed automatically if you change the target
to an earlier .NET Framework version. For more information, see Working with LINQ.
See Also
Multitargeting
Platform compatibility and system requirements
How to: Target a Version of the .NET Framework
10/18/2017 • 2 min to read • Edit Online
This document describes how to target a version of the .NET Framework when you create a project and how to
change the targeted version in an existing Visual Basic, Visual C#, or Visual F# project.
IMPORTANT
For information about how to change the target version for C++ projects, see How to: Modify the Target Framework and
Platform Toolset.
In this topic
Targeting a version when you create a project
Changing the target version
NOTE
In Express editions of Visual Studio, you must create the project first, and then you can change the target, as Changing the
target version describes later in this topic.
NOTE
Typically, only one version of the .NET Framework is installed with Visual Studio. If you want to target another
version, you must first make sure that it's installed. See Visual Studio Multi-Targeting Overview.
3. In the list of installed templates, choose the type of project that you want to create, name the project, and
then choose the OK button.
The list of templates shows only those projects that are supported by the version of the .NET Framework
that you chose.
IMPORTANT
For information about how to change the target version for C++ projects, see How to: Modify the Target
Framework and Platform Toolset.
2. In the left column of the properties window, choose the Application tab.
NOTE
After you create a Windows Store app, you can't change the targeted version of either Windows or the .NET
Framework.
3. In the Target Framework list, choose the version that you want.
4. In the verification dialog box that appears, choose the Yes button.
The project unloads. When it reloads, it targets the .NET Framework version that you just chose.
NOTE
If your code contains references to a different version of the .NET Framework than the one that you targeted, error
messages may appear when you compile or run the code. To resolve these errors, you must modify the references.
See Troubleshooting .NET Framework Targeting Errors.
See Also
Visual Studio Multi-Targeting Overview
.NET Framework Multi-Targeting for ASP.NET Web Projects
Troubleshooting .NET Framework Targeting Errors
Application Page, Project Designer (C#)
Application Page, Project Designer (Visual Basic)
Configuring Projects
How to: Modify the Target Framework and Platform Toolset
Creating Project and Item Templates
10/18/2017 • 2 min to read • Edit Online
Visual Studio project and item templates provide reusable stubs that give users some basic code and structure
that they can use for their own purposes.
Contents of a Template
All project and item templates, whether installed together with Visual Studio or created by you, function by using
the same principles and have similar contents. All templates contain the following items:
The files to be created when the template is used. This includes source code files, embedded resources,
project files, and so on.
One .vstemplate file. This file contains the metadata that provides Visual Studio the information it needs to
display the template in the New Project and Add New Item dialog boxes and create a project or item
from the template. For more information about .vstemplate files, see Template Parameters.
When these files are compressed into a .zip file and put in the correct folder, Visual Studio automatically
displays them. Project templates appear in the My Templates section of the New Project dialog boxes,
and item templates appear in the Add New Item dialog boxes. For more information about template
folders, see How to: Locate and Organize Templates.
Starter Kits
Starter Kits are enhanced templates that can be shared with other members of the community. A Starter Kit
includes code samples that compile, documentation, and other resources to help users learn new tools and
programming techniques while they build useful, real-world applications. The basic contents and procedures for
Starter Kits are identical to those for templates. For more information, see How to: Create Starter Kits.
See Also
How to: Create Project Templates
How to: Create Item Templates
Template Parameters
Customizing Templates
How to: Create Starter Kits
How to: Create Project Templates
10/18/2017 • 1 min to read • Edit Online
This procedure enables you to create a template using the Export Template wizard, which packages your
template in a .zip file. You can also create templates in the VSIX file format for improved deployment by using the
Export Template Wizard extension, or with templates included in the Visual Studio SDK, or you can create
templates manually.
To create a custom project template with the standard Export Template wizard
1. Create a project.
NOTE
Use only valid identifier characters when naming a project that will be the source for a template. A template
exported from a project named with invalid characters can cause compilation errors in future projects based on the
template. For more information on valid identifier characters, see Declared Element Names.
See Also
Creating Project and Item Templates
How to: Create Item Templates
How to: Create Multi-Project Templates
10/18/2017 • 3 min to read • Edit Online
Multi-project templates act as containers for two or more projects. When a project based on a multi-project
template is created from the New Project dialog box, every project in the template is added to the solution.
A multi-project template must include the following items, compressed into a .zip file:
A root .vstemplate file for the entire multi-project template. This root .vstemplate file contains the metadata
that the New Project dialog box displays, and specifies where to find the .vstemplate files for the projects in
this template. This file must be located at the root of the .zip file.
One or more folders that contain the files that are required for a complete project template. This includes all
code files for the project, and also a .vstemplate file for the project.
For example, a multi-project template .zip file that has two projects could have the following files and
directories:
MultiProjectTemplate.vstemplate
\Project1\Project1.vstemplate
\Project1\Project1.vbproj
\Project1\Class.vb
\Project2\Project2.vstemplate
\Project2\Project2.vbproj
\Project2\Class.vb
The root .vstemplate file for a multi-project template differs from a single-project template in the following
ways:
The Type attribute of the VSTemplate element contains the value ProjectGroup . For example:
The TemplateContent element contains a ProjectCollection element that has one or more
ProjectTemplateLink elements that define the paths to the .vstemplate files of the included projects. For
example:
<TemplateContent>
<ProjectCollection>
<ProjectTemplateLink>
Project1\Project1.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink>
Project2\Project2.vstemplate
</ProjectTemplateLink>
</ProjectCollection>
</TemplateContent>
Multi-project templates also behave differently than normal templates. Multi-project templates have the
following unique characteristics:
Individual projects in a multi-project template cannot be assigned names by the New Project dialog box.
Instead, use the ProjectName attribute on the ProjectTemplateLink element to specify the name for each
project. For more information, see the first example in the following section.
Multi-project templates can contain projects written in different languages, but the entire template itself can
only be put in one category by using the ProjectType element.
To create a multi-project template
1. Create the projects to include in the multi-project template.
2. Create .vstemplate files for every project. For more information, see How to: Create Project Templates.
3. Create a root .vstemplate file that to contain the metadata for the multi-project template. For more
information, see the first example in the following section.
4. Select the files and folders to include in your template, right-click the selection, click Send To, and then click
Compressed (zipped) Folder. The files and folders are compressed into a .zip file.
5. Put the .zip template file in the Visual Studio project template directory. By default, this directory is \My
Documents\Visual Studio Version\Templates\ProjectTemplates\.
Example
This example shows a basic multi-project root .vstemplate file. In this example, the template contains two projects,
My Windows Application and My Class Library . The ProjectName attribute on the ProjectTemplateLink element
sets the name for Visual Studio to assign this project. If the ProjectName attribute does not exist, the name of the
.vstemplate file is used as the project name.
Example
This example uses the SolutionFolder element to divide the projects into two groups, Math Classes and
Graphics Classes . The template contains four projects, two of which are placed in each solution folder.
<VSTemplate Version="2.0.0" Type="ProjectGroup"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Multi-Project Template Sample</Name>
<Description>An example of a multi-project template</Description>
<Icon>Icon.ico</Icon>
<ProjectType>VisualBasic</ProjectType>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<SolutionFolder Name="Math Classes">
<ProjectTemplateLink ProjectName="MathClassLib1">
MathClassLib1\MyTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="MathClassLib2">
MathClassLib2\MyTemplate.vstemplate
</ProjectTemplateLink>
</SolutionFolder>
<SolutionFolder Name="Graphics Classes">
<ProjectTemplateLink ProjectName="GraphicsClassLib1">
GraphicsClassLib1\MyTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="GraphicsClassLib2">
GraphicsClassLib2\MyTemplate.vstemplate
</ProjectTemplateLink>
</SolutionFolder>
</ProjectCollection>
</TemplateContent>
</VSTemplate>
See Also
Creating Project and Item Templates
Visual Studio Template Schema Reference
How to: Create Project Templates
Visual Studio Template Schema Reference
SolutionFolder Element (Visual Studio Templates)
ProjectTemplateLink Element (Visual Studio Templates)
How to: Create Item Templates
10/18/2017 • 4 min to read • Edit Online
The steps in the first procedure of this topic show you how to create an item template by using the Export
Template wizard. If your template will consist of multiple files, see How to: Create Multi-file Item Templates.
The wizard does a lot of work for you to create the basic template, but in many cases you will need to manually
modify the .vstemplate file after you have exported the template. For example, if you want the item to appear in
the Add New Item dialog for a Windows 8.x Store app project, you'll have to perform a few extra steps. The
second procedure in this topic helps you accomplish that task.
To specify that your template should only appear for only certain project sub-types, such as Office, Database or
Web, see this section.
In some cases you may want or need to create an item template manually from scratch. The third procedure
shows how to do that.
See the Visual Studio Template Schema Reference for information about the elements that can be used in the
.vstemplate file.
To add a custom project item template to the Add New Item dialog box
1. Create or open a project in Visual Studio.
2. Add an item to the project and modify it if you want to.
3. Modify the code file to indicate where parameter replacement should take place. For more information, see
How to: Substitute Parameters in a Template.
4. On the Project menu, click Export Template.
5. Click Item Template, select the project that contains the item, and click Next.
6. Select the item for which you want to create a template, and click Next.
7. Select the assembly references to include in the template, and click Next.
8. Type the icon file name, preview image, template name, and template description, and click Finish.
The files for the template are added to a .zip file and copied whatever directory you specify in the dialog.
The default location is ..\Users\<username>\Documents\Visual Studio <Version>\My Exported
Templates\ folder.
WARNING
In earlier versions of Visual Studio, the default location is ..\Users\<username>\Documents\Visual Studio
<Version>\Templates\ItemTemplates.
For a Windows 8.1 store C# project, in the .vstemplate file, add the following XML within the opening and
closing <TemplateData> tag: <TemplateGroupID>WinRT-Managed</TemplateGroupID> .
A C++ Windows 8.1 store project uses a value of WinRT-Native-6.3 . For Windows 10 and other project
types, see TemplateGroupID Element (Visual Studio Templates).
The following example shows the entire contents of a .vstemplate file after the line of XML
<TemplateGroupID>WinRT-Managed</TemplateGroupID> has been added to it. This example is specific to C#
projects. You can modify the and < TemplateGroupID> elements to specify other language and project
types.
For other possible TemplateGroupID values, see TemplateGroupID Element (Visual Studio Templates)). For
the complete .vstemplate reference, see Visual Studio Template Schema Reference
5. In Visual Studio, save the .vstemplate file and close it.
6. Copy and paste the .vstemplate file back to the .zip file located in the ..\Users\username\Documents\Visual
Studio Version\Templates\ItemTemplates\ folder.
If the Copy File dialog box appears, choose the Copy and Replace option.
You can now add an item based on this template to a Windows 8.x Store project by using the Add New
Item dialog box.
For more information about parameter names, see Template Parameters.
To enable templates for specific project sub-types
1. The development environment enables you to make project items available from the Add Item dialog box
for certain projects. Use this procedure to make custom items available for Windows, Web, Office, or
database projects.
Locate the ProjectType element in the .vstemplate file for the item template.
Add a ProjectSubType element immediately after the ProjectType element.
2. Set the text value of the element to one of the following values:
a. Windows
b. Office
c. Database
d. Web
For example: <ProjectSubType>Database</ProjectSubType> .
The following example shows an item template available for Office projects.
To manually create an item template without using the Export Template wizard
1. Create a project and project item.
2. Modify the project item until it is ready to be saved as a template.
3. As appropriate, modify the code file to indicate where parameter replacement should occur. For more
information about parameter replacement, see How to: Substitute Parameters in a Template.
4. Create an XML file and save it by using a .vstemplate file name extension, in the same directory as your
new item template.
5. Author the .vstemplate XML file to provide item template metadata. For more information, see Visual
Studio Template Schema Reference and the example in the previous section.
6. Save the .vstemplate file and close it.
7. In Windows Explorer, select the files you want to include in your template, right-click the selection, click
Send To, and then click Compressed (zipped) Folder. The files that you selected are compressed into a .zip
file.
8. Copy the .zip file and paste it in the user item template location. In Visual Studio 2017, the default directory
is ..\Users\<username>\Documents\Visual Studio 2017\Templates\ItemTemplates\. For more information,
see How to: Locate and Organize Project and Item Templates.
See Also
Creating Project and Item Templates
How to: Create Multi-file Item Templates
Visual Studio Template Schema Reference
How to: Create Multi-file Item Templates
10/18/2017 • 1 min to read • Edit Online
Item templates may only specify one item, but sometimes the item is made up of multiple files. For example, a
Windows Forms item template for Visual Basic requires the following three files:
A .vb file that contains the code for the form.
A .designer.vb file that contains the designer information for the form.
A .resx file that contains the embedded resources for the form.
Multi-file item templates require parameters to ensure the correct file name extensions are used when the
item is created in Visual Studio. If you create an item template by using the Export Template wizard, these
parameters are automatically generated, and no further editing is required. The following steps explain how
to use parameters to ensure that the correct file name extensions are created.
To manually create a multi-file item template
1. Create the item template as you would create a single-file item template. For more information, see How to:
Create Item Templates.
2. Add TargetFileName attributes to every ProjectItem element. Set the values of the TargetFileName
attributes to $fileinputname$.FileExtension, where FileExtension is the file name extension of the file that is
being included in the template. For example:
<ProjectItem TargetFileName="$fileinputname$.vb">
Form1.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.Designer.vb">
Form1.Designer.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
Form1.resx
</ProjectItem>
When an item derived from this template is added to a project, the file names will be based on the name
that the user typed in the Add New Item dialog box.
3. Select the files to be included in your template, right-click the selection, click Send To, and then click
Compressed (zipped) Folder. The files that you selected are compressed into a .zip file.
4. Put the .zip file in the user item template location. By default, the directory is \My Documents\Visual Studio
Version\Templates\ItemTemplates\. For more information, see How to: Locate and Organize Templates.
Example
The following example shows a Visual Studio Windows Forms template. When an item is created based on this
template, the names of the three files created will match the name entered in the Add New Item dialog box.
<VSTemplate Version="2.0.0" Type="Item"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>Multi-file Item Template</Name>
<Icon>Icon.ico</Icon>
<Description>An example of a multi-file item template</Description>
<ProjectType>VisualBasic</ProjectType>
</TemplateData>
<TemplateContent>
<ProjectItem TargetFileName="$fileinputname$.vb" SubType="Form">
Form1.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.Designer.vb">
Form1.Designer.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
Form1.resx
</ProjectItem>
</TemplateContent>
</VSTemplate>
See Also
Creating Project and Item Templates
How to: Create Item Templates
Template Parameters
How to: Substitute Parameters in a Template
How to: Manually Create Web Templates
10/18/2017 • 1 min to read • Edit Online
Creating a Web template is different than creating other kinds of templates. Because Web project templates appear
in the Add New Web Site dialog box, and Web project items are categorized by programming language, the
.vstemplate file must specify the template as a Web template and identify the programming language.
NOTE
Web templates must contain a empty .webproj file that is specified by using the File attribute of the Project element.
Although Web projects do not require project files, this file is required so that a Web template functions correctly.
<TemplateData>
...
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
...
</TemplateData>
7. Select the files in your template (this includes the .vstemplate file), right-click the selection, click Send To,
and then click Compressed (zipped) Folder. The files are compressed into a .zip file.
8. Put the .zip template file in the Visual Studio project template directory. By default, this directory is \My
Documents\Visual Studio Version\My Exported Templates\.
Example
The following example shows a basic .vstemplate file for a Web project template.
<VSTemplate Version="2.0.0" Type="Project"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">>
<TemplateData>
<Name>MyWebProjecStarterKit</Name>
<Description>A simple Web template</Description>
<Icon>icon.ico</Icon>
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
<DefaultName>WebSite</DefaultName>
</TemplateData>
<TemplateContent>
<Project File="WebApplication.webproj">
<ProjectItem>icon.ico</ProjectItem>
<ProjectItem OpenInEditor="true">Default.aspx</ProjectItem>
<ProjectItem>Default.aspx.cs</ProjectItem>
</Project>
</TemplateContent>
</VSTemplate>
See Also
Creating Project and Item Templates
Visual Studio Template Schema Reference
How to: Create Starter Kits
10/18/2017 • 1 min to read • Edit Online
A Starter Kit contains code for a complete application and documentation on how to modify or expand the
application. Creating a Starter Kit is fundamentally the same as creating a normal project template, the only
difference being that a Starter Kit contains documentation files that are set to open when a project based on the
Starter Kit is created.
Creating a Template
After you have completed the project and the documentation, you are ready to create the project template for the
Starter Kit. This process is exactly the same as creating a project template.
The following topics contain information about creating templates.
How to: Create Project Templates
Explains how to use the Export Template wizard to create a template.
How to: Update Existing Templates
Describes how to edit an exported template. Use this procedure to modify the .vstemplate file to customize your
Starter Kit.
See Also
Creating Project and Item Templates
Customizing Templates
Visual Studio Template Schema Reference
How to: Locate and Organize Project and Item
Templates
10/18/2017 • 4 min to read • Edit Online
Template files must be placed in a location that Visual Studio recognizes so that the templates will appear in the
New Project and Add New Item dialog boxes. You can create custom subcategories for templates so that the
subcategories will also appear in the user interface.
Locating Templates
By default, Visual Studio searches two locations for project and item templates. If a compressed file that includes a
.vstemplate file exists in these locations, a template will appear in the New Project or Add New Item dialog
boxes.
Installed Templates
By default, templates installed together with the product are located in:
\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\Language\Locale\
\VisualStudioInstallationDirectory\Common7\IDE\ProjectTemplates\Language\Locale\
For example, the following directory contains the Visual Studio project templates for English:
C:\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\VisualBasic\1033\
Custom Templates
By default, custom templates are located in:
\My Documents\Visual Studio Version\Templates\ProjectTemplates\Language\
\My Documents\Visual Studio Version\Templates\ItemTemplates\Language\
For example, the following directory contains custom Visual C# project templates:
C:\Documents and Settings\UserName\My Documents\Visual Studio
Version\Templates\ProjectTemplates\Visual C#\
Custom templates do not include a subdirectory for localized templates. You can change the default
directory for custom templates in the Options dialog box, under Environment\Projects and Solutions.
Organizing Templates
The categories in the New Project and Add New Item dialog boxes reflect the directory structures that exist in
the installed and custom template locations. You can modify these directory structures to organize your templates
in a way that makes sense to you.
NOTE
You cannot create a new category at the programming language level. New categories can only be created within each
language.
If the directory structures for installed and custom templates for a particular language do not have the same
structure (that is, there are directories under one folder that do not exist under the other) the set of categories that
appear in the New Project dialog will be the merger of all categories.
Organizing Installed Templates
You can organize installed templates by creating subdirectories in the programming language folder. These
subdirectories appear in the New Project and Add New Item dialog boxes as virtual folders within each
language.
To c r e a t e n e w i n st a l l e d p r o j e c t t e m p l a t e c a t e g o r i e s
1. Create a folder in the language folder of the installed template directory. For example, to create an Office
category for Visual Studio project templates you would create the following directory:
\VisualStudioInstallationDirectory\Common7\IDE\ProjectTemplates\VisualBasic\1033\Office\
2. Place all the templates for this category in the new folder.
3. Close all instances of Visual Studio.
4. On the Start menu, click Run, type cmd, and click OK.
5. At the command prompt, locate the directory that contains devenv.exe, and type devenv
/installvstemplates.
6. Run Visual Studio.
7. On the File menu, click New, and then click Project.
8. Verify that the Office category appears in the New Project dialog box, in the Project types pane, under
Visual Basic.
You can also group a subset of the project item templates into a custom folder.
To c r e a t e n e w i n st a l l e d i t e m t e m p l a t e c a t e g o r i e s
1. Create a folder in the language folder of the installed template directory. For example, to create a Web
category for Visual C# item templates you would create the following directory:
\VisualStudioInstallationDirectory\Common7\IDE\ItemTemplates\CSharp\1033\Web\
2. Place all templates for this category in the new folder.
3. Close all instances of Visual Studio.
4. On the Start menu, click Run, type cmd, and click OK.
5. At the command prompt, locate the directory that contains devenv.exe, and type devenv /setup.
6. Run Visual Studio.
7. Create a project or open an existing project.
8. On the Project menu, click Add New Item.
9. Verify that the Web category appears in the Add New Item dialog box, in the Project types pane.
Organizing Custom Templates
Custom templates can be organized into their own categories by adding new folders in the custom template
location. The New Project dialog box reflects any changes you make to your template categories.
To c r e a t e n e w c u st o m p r o j e c t t e m p l a t e c a t e g o r i e s
1. Create a folder in the language folder in the custom project template directory. For example, to create a
HelloWorld category for Visual C# templates, you would create the following directory:
\My Documents\Visual Studio Version\Templates\ProjectTemplates\CSharp\HelloWorld\
2. Place all the templates for this category in the new folder.
3. On the File menu, click New, and then click Project.
4. Verify that the HelloWorld category appears in the New Project dialog box, in the Project types pane,
under Visual C#.
You can also group a subset of the custom item templates into a custom folder.
To c r e a t e n e w c u st o m i t e m t e m p l a t e c a t e g o r i e s
1. Create a folder in the language folder in the custom item template directory. For example, to create a
HelloWorld category for Visual C# templates you would create the following directory:
\My Documents\Visual Studio Version\Templates\ItemTemplates\CSharp\HelloWorld\
2. Place all the templates for this category in the new folder.
3. Create a project or open an existing project.
4. On the Project menu, click Add New Item.
5. Verify that the HelloWorld category appears in the Add New Item dialog box, in the Project types pane.
Displaying Templates in Parent Categories
You can enable templates in subcategories to be displayed in their parent categories by using the
NumberOfParentCategoriesToRollUp element in the .vstemplate file. These steps are identical for both project
templates and item templates.
To d i sp l a y t e m p l a t e s i n p a r e n t c a t e g o r i e s
<TemplateData>
...
<NumberOfParentCategoriesToRollUp>
1
</NumberOfParentCategoriesToRollUp>
...
</TemplateData>
See Also
Customizing Templates
Visual Studio Template Schema Reference
NumberOfParentCategoriesToRollUp (Visual Studio Templates)
How to: Create Project Templates
How to: Create Item Templates
Customizing Project and Item Templates
10/18/2017 • 1 min to read • Edit Online
After project and item templates have been created, you still have the ability to further customize them to meet
your needs.
For example, you can perform the following tasks:
Modify and export an existing template as a custom template.
For more information, see How to: Update Existing Templates.
Pass custom parameters into a template to replace existing values.
For more information, see How to: Substitute Parameters in a Template.
Customize the wizards that create projects from templates.
For more information, see How to: Use Wizards with Project Templates.
Related Sections
Creating Project and Item Templates
How to: Troubleshoot Templates
How to: Create Project Templates
How to: Create Item Templates
How to: Create Starter Kits
Visual Studio Template Schema Reference
IWizard
How to: update existing templates
10/20/2017 • 1 min to read • Edit Online
After you create a template and compress the files into a .zip file, you may want to modify the template. You can do
this by manually changing the files in the template, or by exporting a new template from a project that is based on
the template.
See also
Customizing Templates
Creating Project and Item Templates
Visual Studio Template Schema Reference
Template Parameters
How to: Create Starter Kits
How to: Substitute Parameters in a Template
10/18/2017 • 1 min to read • Edit Online
You may replace template parameters such as class names and namespaces when a file based on a template is
created. For a complete list of template parameters, see Template Parameters.
Procedure
You may replace parameters in the files of a template whenever a project based on that template is created. This
procedure explains how to create a template that replaces the name of a namespace with the safe project name
when a new project is created with the template.
To use a parameter to replace namespace name with the project name
1. Insert the parameter in one or more of the code files in the template. For example:
namespace $safeprojectname$
NOTE
Template parameters are written in the format $parameter$.
2. In the .vstemplate file for the template, locate the ProjectItem element that includes this file.
3. Set the ReplaceParameters attribute to true for the ProjectItem element. For example:
<ProjectItem ReplaceParameters="true">Class1.cs</ProjectItem>
See Also
Creating Project and Item Templates
Template Parameters
Visual Studio Template Schema Reference
ProjectItem Element (Visual Studio Item Templates)
How to: Troubleshoot Templates
10/18/2017 • 1 min to read • Edit Online
If a template fails to load in the development environment, there are several ways to locate the problem.
NOTE
To get IntelliSense support while authoring the .vstemplate file, add a xmlns attribute to the VSTemplate element
and assign it a value of http://schemas.microsoft.com/developer/vstemplate/2005.
See Also
Customizing Templates
Creating Project and Item Templates
Visual Studio Template Schema Reference
Visual Studio Template Reference
10/18/2017 • 1 min to read • Edit Online
The following links provide reference information about the different aspects of Visual Studio project and item
templates.
In This Section
Visual Studio Template Schema Reference
Describes the XML elements used in .vstemplate files.
Template Parameters
Describes the parameters available for project and item templates.
Microsoft.VisualStudio.TemplateWizard
Describes the IWizard interface and related types.
Related Sections
How to: Create Project Templates
How to: Create Item Templates
Customizing Templates
How to: Create Starter Kits
Template Parameters
10/18/2017 • 2 min to read • Edit Online
By using parameters in your templates, you can replace the values of key portions of the template, such as class
names and namespaces, when the template is instantiated. These parameters are replaced by the template
wizard that runs in the background when a user clicks OK in the New Project or Add New Item dialog boxes.
namespace $safeprojectname$
NOTE
Template parameters are case-sensitive.
PARAMETER DESCRIPTION
GUID [1-10] A GUID used to replace the project GUID in a project file.
You can specify up to 10 unique GUIDs (for example,
guid1) .
itemname The name provided by the user in the Add New Item dialog
box.
projectname The name provided by the user in the New Project dialog
box.
safeitemname The name provided by the user in the Add New Item dialog
box, with all unsafe characters and spaces removed.
safeprojectname The name provided by the user in the New Project dialog
box, with all unsafe characters and spaces removed.
webnamespace The name of the current Web site. This parameter is used in
the Web form template to guarantee unique class names. If
the Web site is at the root directory of the Web server, this
template parameter resolves to the root directory of the Web
Server.
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace $safeprojectname$
{
public class Class1
{
public Class1()
{
}
}
}
In the .vstemplate file for the project template, include the following XML when you reference the file Class1.cs:
<TemplateContent>
<ProjectItem ReplaceParameters="true">
Class1.cs
</ProjectItem>
...
</TemplateContent>
See Also
Customizing Templates
Write code in the code editor
10/18/2017 • 9 min to read • Edit Online
The Visual Studio editor provides many features that make it easier for you to write and manage your code and
text. You can expand and collapse different blocks of code by using outlining. You can learn more about the code
by using IntelliSense, the Object Browser, and the Call Hierarchy. You can find code by using features such as Go
To, Go To Definition, and Find All References. You can insert blocks of code with code snippets, and you can
generate code by using features such as Generate From Usage. If you have never used the Visual Studio editor
before, see Editing Your Code for a quick overview.
You can view your code in a number of different ways. By default, Solution Explorer shows your code organized
by files. You can click on the Class View tab at the bottom of the window to view your code organized by classes.
You can search and replace text in single or multiple files. For more information, see Finding and Replacing Text.
You can use regular expressions to find and replace text. For more information, see Using Regular Expressions in
Visual Studio.
The different Visual Studio languages offer different sets of features, and in some cases the features behave
differently in different languages. Many of these differences are specified in the descriptions of the features, but
for more information you can see the sections on specific Visual Studio languages.
IMPORTANT
The Visual Studio edition and the settings you are using may affect the features in the IDE. They might differ from those
described in this topic.
Editor Features
Syntax Coloring Some syntax elements of code and markup files are colored
differently to distinguish them. For example, keywords (such
as using in C# and Imports in Visual Basic) are one color,
but types (such as Console and Uri ) are another color.
Other syntax elements are also colorized, such as string
literals and comments. C++ uses color to differentiate among
types, enumerations, and macros, among other tokens.
You can see the default color for each type, and you can
change the color for any specific syntax element in the Fonts
and Colors, Environment, Options Dialog Box, which you can
open from the Tools menu.
Error and Warning Marks As you add code and build your solution, you may see (a)
different-colored wavy underlines (known as squiggles) or (b)
light bulbs appearing in your code. Red squiggles denote
syntax errors, blue denotes compiler errors, green denotes
warnings, and purple denotes other types of errors. Light
bulbs suggest fixes for problems and make it easy to apply
the fix.
You can see the default color for each error and warning
squiggle in the Tools/Options/Environment/Fonts and
Colors dialog box. Look for Syntax Error, Compiler Error,
Warning, and Other Error.
Brace Matching When the insertion point is placed on an open brace in a code
file, both it and the closing brace are highlighted. This feature
gives you immediate feedback on misplaced or missing
braces. You can turn brace matching on or off with the
Automatic Delimiter Highlighting setting
(Tools/Options/Text Editor). You can change the highlight
color in the Fonts and Colors setting
(Tools/Options/Environment). Look for Brace Matching
(Highlight) or Brace Matching (Rectangle).
Structure Visualizer Dotted lines connect matching braces in code files, making it
easier to see opening and closing brace pairs. This can help
you find code in your codebase more quickly. You can turn
these lines on or off with the Show structure guidelines in
the Display section of the Tools/Options/Text
Editor/General page.
Line Numbers Line numbers can be displayed in the left margin of the code
window. They are not displayed by default. You can turn this
option on in the Text Editor All Languages settings
(Tools/Options/Text Editor/All Languages). You can
display line numbers for individual programming languages
by changing the settings for those languages
(Tools/Options/Text Editor/<language>). For line numbers
to print, you must select Include line numbers in the Print
dialog box.
Change Tracking The color of the left margin allows you to keep track of the
changes you have made in a file. Changes you have made
since the file was opened but not saved are denoted by a
yellow bar on the left margin (known as the selection margin).
After you have saved the changes (but before closing the file),
the bar turns green. If you undo a change after you have
saved the file, the bar turns orange. To turn this feature off
and on, change the Track changes option in the Text Editor
settings (Tools/Options/Text Editor).
Selecting Code and Text You can select text either in the standard continuous stream
mode or in box mode, in which you select a rectangular
portion of text instead of a set of lines. To make a selection in
box mode, press ALT as you drag the mouse over the
selection (or press ALT + SHIFT + <arrow key>). The selection
includes all of the characters within the rectangle defined by
the first character and the last character in the selection.
Anything typed or pasted into the selected area is inserted at
the same point on each line.
Zoom You can zoom in or out in any code window by pressing and
holding the CTRL key and moving the scroll wheel on the
mouse (or CTRL + SHIFT + . to increase and CTRL + SHIFT + ,
to decrease). You can also use the Zoom box in the lower left
corner of the code window to set a specific zoom percentage.
The zoom feature does not work in tool windows.
Virtual Space By default, lines in Visual Studio editors end after the last
character, so that the RIGHT ARROW key at the end of a line
moves the cursor to the beginning of the next line. In some
other editors a line does not end after the last character, and
you can place your cursor anywhere on the line. You can
enable virtual space in the editor in the Tools/Options/Text
Editor/All Languages settings. Note that you can enable
either Virtual Space or Word Wrap, but not both.
Printing You can use the options in the Print dialog box to include line
numbers or hide collapsed regions of code when you print a
file. In the Page Setup dialog box, you can also choose to
print the full path and the name of the file by choosing Page
header.
Global Undo and Redo The Undo Last Global Action and Redo Last Global Action
commands on the Edit menu undo or redo global actions
that affect multiple files. Global actions include renaming a
class or namespace, performing a find-and-replace operation
across a solution, refactoring a database, or any other action
that changes multiple files. You can apply the global undo
and redo commands to actions in the current Visual Studio
session, even after you close the solution in which an action
was applied.
Format Document Sets the proper indentation of lines of code and moves curly
braces to separate lines in the document.
Format Selection Sets the proper indentation of lines of code and moves curly
braces to separate lines in the selection.
Move selected Lines Up Moves the selected line up one line. Shortcut: ALT + UP
ARROW.
Move Selected Lines Down Moves the selected line down one line. Shortcut: ALT +
DOWN ARROW.
Delete Horizontal White Space Deletes tabs or spaces at the end of the current line.
View White Space Displays spaces as raised dots, and tabs as arrows. The end of
a file is displayed as a rectangular glyph. If
Tools/Options/Text Editor/All Languages/Word
Wrap/Show visible glyphs for word wrap is selected, that
glyph is also displayed.
Word Wrap Causes all the lines in a document to be visible in the code
window. You can turn word wrap off and on in the Text Editor
All Languages settings (Tools/Options/ Text Editor/All
Languages).
Comment Selection Adds comment characters to the selection or the current line.
Increase Line Indent Adds a tab (or the equivalent spaces) to the selected lines or
the current line.
Decrease Line Indent Removes a tab (or the equivalent spaces) from the selected
lines or the current line.
Select Tag Content In a document that contains tags (for example, XML or
HTML), selects the content.
See Also
Visual Studio IDE
Finding and Replacing Text
10/18/2017 • 3 min to read • Edit Online
You can find and replace text in the Visual Studio code editor, and certain text-based output windows such as the
Find Results windows, using the Find and Replace control or Find/Replace in Files. You can also search and
replace in some designer windows, such as the XAML designer and the Windows Forms designer, and tool
windows
You can scope searches to the current document, the current solution, or a custom set of folders. You can also
specify a set of file name extensions for multi-file searches. You can customize search syntax by using .NET regular
expressions.
To find and replace regular expressions, see Using Regular Expressions in Visual Studio.
TIP
The Find/Command box is still available as a toolbar control, but is no longer visible by default. You can display the
Find/Command box by choosing Add or Remove Buttons on the Standard toolbar and then choosing Find. For more
information, see Find/Command Box.
Find/Replace in Files
Find/Replace in Files works like the Find and Replace control, except that you can define a scope for your
search. Not only can you search the current open file in the editor, but you can also search all open documents, the
entire solution, the current project, and selected folder sets. You can also search by file name extension. To access
the Find/Replace in Files dialog box, choose Find and Replace on the Edit menu (or CTRL+SHIFT+F).
When you choose Find All, a Find Results window opens and lists the matches for your search. Selecting a result
in the list displays the associated file and highlights the match. If the file is not already open for editing, it is
opened in a preview tab in the right side of the tab well. You can use the Find control to search through the Find
Results list.
Creating Custom Search Folder Sets
You can define a search scope by choosing the Choose Search Folders button (it looks like ...) next to the Look in
box. In the Choose Search Folders dialog box, you can specify a set of folders in which to search, and you can
save the specification so that you can reuse it later. You can specify folders on a remote machine only if you have
mapped its drive to the local machine.
Creating Custom Component Sets
You can define component sets as your search scope by choosing the Edit Custom Component Set button next
to the Look in box. You can specify installed .NET or COM components, Visual Studio projects that are included in
your solution, or any assembly or type library (.dll, .tlb, .olb, .exe, or .ocx). To search references, select the Look in
references box.
See Also
Using Regular Expressions in Visual Studio
Using Regular Expressions in Visual Studio
10/18/2017 • 3 min to read • Edit Online
Visual Studio uses .NET Framework regular expressions to find and replace text. For more information about .NET
regular expressions, see .NET Framework Regular Expressions.
Before Visual Studio 2012, Visual Studio used custom regular expression syntax in the Find and Replace windows.
See Visual Studio Regular Expression Conversions for an explanation of how to convert some of the more
commonly-used custom regular expression symbols to the .NET versions.
TIP
In Windows operating systems, most lines end in "\r\n" (a carriage return followed by a new line). These characters are not
visible, but are present in the editor and are passed to the .NET Regular Expression service.
TIP
For information about regular expressions that are used in replacement patterns, see Substitutions. To use a numbered
capture group, the syntax is $1 to specify the numbered group and (x) to specify the group in question. For example,
the grouped regular expression (\d)([a-z]) finds four matches in the following string: 1a 2b 3c 4d. The replacement
string z$1 converts that string to z1 z2 z3 z4.
Match any single character (except a . a.o matches "aro" in "around" and
line break) "abo" in "about" but not "acro" in
"across".
Match zero or more occurrences of the * a*r matches "r" in "rack", "ar" in "ark",
preceding expression (match as many and "aar" in "aardvark"
characters as possible)
Match any character zero or more .* c.*e matches "cke" in "racket", "comme"
times (Wildcard *) in "comment", and "code" in "code"
Match one or more occurrences of the + e.+e matches "eede" in "feeder" but
preceding expression (match as many not "ee".
characters as possible)
Match any character one or more times .+ e.+e matches "eede" in "feeder" but not
(Wildcard ?) "ee".
Match zero or more occurrences of the *? e.*?e matches "ee" in "feeder" but
preceding expression (match as few not "eede".
characters as possible)
PURPOSE EXPRESSION EXAMPLE
Match one or more occurrences of the +? e.+?e matches "ente" and "erprise" in
preceding expression (match as few "enterprise", but not the whole word
characters as possible) "enterprise".
Anchor the match string to the ^ ^car matches the word "car" only
beginning of a line or string when it appears at the beginning of a
line.
Anchor the match string to the end of \r?$ End\r?$ matches "end" only when it
a line appears at the end of a line.
Match any single character in a set [abc] b[abc] matches "ba", "bb", and "bc".
Match any character that is not in a [^abc] be[^n-t] matches "bef" in "before",
given set of characters "beh" in "behind", and "bel" in "below",
but not "beneath".
Specify the number of occurrences of {x}, where x is the number of x(ab){2}x matches "xababx", and
the preceding character or group occurrences x(ab){2,3}x matches "xababx" and
"xabababx" but not "xababababx".
Match text in a Unicode character class, \p{X} \p{Lu} matches "T" and "D" in
where "X" is the Unicode number. For "Thomas Doe".
more information about Unicode
character classes, see
Match a line break (ie a carriage return \r?\n End\r?\nBegin matches "End" and
followed by a new line). "Begin" only when "End" is the last
string in a line and "Begin" is the first
string in the next line.
Match any alphanumeric character \w a\wd matches "add" and "a1d" but
not "a d".
Match a Unicode character \uXXXX where XXXX specifies the \u0065 matches the character "e".
Unicode character value.
Match a string inside quotes ((\".+?\")|('.+?')) Matches any string inside single or
double quotes.
See Also
Finding and Replacing Text
Find/Command Box
10/18/2017 • 1 min to read • Edit Online
You can search for text and run Visual Studio commands from the Find/Command box. The Find/Command box
is still available as a toolbar control, but is no longer visible by default. You can display the Find/Command box by
choosing Add or Remove Buttons on the Standard toolbar and then choosing Find.
To run a Visual Studio command, preface it with a greater than (>) sign.
The Find/Command box retains the last 20 items entered and displays them in a drop-down list. You can navigate
through the list by choosing the arrow keys.
Find/Command Box
Entering Commands
To use the Find/Command box to issue a single Visual Studio command or alias rather than search for text, enter
the Visual Studio command, prefaced with a greater than (>) symbol. For example:
Alternatively, you can also use the Command window to enter and execute single or multiple commands. Some
commands or aliases can be entered and executed by themselves; others have required arguments in their syntax.
For a list of commands that have arguments, see Visual Studio Commands.
Escape Characters
A caret (^) character in a command line means that the character immediately following it is interpreted literally,
rather than as a control character. This can be used to embed straight quotation marks ("), spaces, leading slashes,
carets, or any other literal characters in a parameter or switch value, with the exception of switch names. For
example,
A caret functions the same whether it is inside or outside quotation marks. If a caret is the last character on the line,
it is ignored.
See Also
Command Window
Finding and Replacing Text
Find in Files
10/18/2017 • 3 min to read • Edit Online
Find in Files allows you to search a specified set of files. The matches found and actions taken are listed in the
Find Results window selected in Result options.
You can use any of the following methods to display Find in Files in the Find and Replace window.
To display Find in Files
1. On the menu bar, choose Edit, Find and Replace.
2. Choose Find in Files.
To cancel a Find operation, press CTRL + BREAK.
NOTE
The Find and Replace tool does not search directories with the Hidden or System attribute set.
Find what
To search for a new text string or expression, specify it in the box. To search for any of the 20 strings that you
searched for most recently, open the list, and choose the string for which you want to search. Choose the adjacent
Expression Builder button if you want to use one or more regular expressions in your search string. For more
information, see Using Regular Expressions in Visual Studio.
Look in
The option chosen from the Look in drop-down list determines whether Find in Files searches only in currently
active files or in all files stored within certain folders. Select a search scope from the list or click the Browse (...)
button to display the Choose Search Folders dialog box and to enter your own set of directories. You can also
type a path directly into the Look in box.
WARNING
With the Entire Solution or Current Project options, project and solution files are not searched. If you want to look in
project files, choose a search folder.
NOTE
If the Look in option selected causes you to search a file that you have checked out from source code control, only the
version of that file which has been downloaded to your local machine is searched.
Include subfolders
Specifies that subfolders of the Look in folder will be searched.
Find options
You can expand or collapse the Find options section. The following options can be selected or cleared:
Match case
When selected, a Find Results search will be case-sensitive
Match whole word
When selected, the Find Results windows will only return whole word matches.
Use Regular Expressions
If this check box is selected, you can use special notations to define patterns of text to match in the Find what or
Replace with text boxes. For a list of these notations, see Using Regular Expressions in Visual Studio.
Look at these file types
This list indicates the types of files to search through in the Look in directories. If this field is blank, all of the files in
the Look in directories will be searched.
Select any item in the list to enter a preconfigured search string that will find files of those particular types.
Result options
You can expand or collapse the Result options section. The following options can be selected or cleared:
Find results 1 window
When selected, the results of the current search will replace the content of the Find Results 1 window. This window
opens automatically to display your search results. To open this window manually, select Other Windows from the
View menu and choose Find Results 1.
Find results 2 window
When selected, the results of the current search will replace the content of the Find Results 2 window. This window
opens automatically to display your search results. To open this window manually, select Other Windows from the
View menu and choose Find Results 2.
Display file names only
Displays a list of files containing search matches rather than displaying the search matches themselves.
Append results
Appends the results from the search to the previous search results.
See Also
Finding and Replacing Text
Replace in Files
Visual Studio Commands
Replace in Files
10/18/2017 • 4 min to read • Edit Online
Replace in Files allows you to search the code of a specified set of files for a string or expression, and change
some or all of the matches found. The matches found and actions taken are listed in the Find Results window
selected in Result options.
NOTE
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Personalize the Visual Studio IDE.
You can use any of the following methods to display Replace in Files in the Find and Replace window.
To display Replace in Files
1. On the Edit menu, expand Find and Replace.
2. Choose Replace in Files.
— or —
If the Find and Replace window is already open, on the toolbar, choose Replace in Files.
Find what
To search for a new text string or expression, specify it in the box. To search for any of the 20 strings that you
searched for most recently, open the list, and choose the string for which you want to search. Choose the adjacent
Expression Builder button if you want to use one or more regular expressions in your search string. For more
information, see Using Regular Expressions in Visual Studio.
Replace With
To replace instances of the string in the Find what box with another string, enter the replacement string in the
Replace With box. To delete instances of the string in the Find what box, leave this field blank. Open the list to
display the 20 strings for which you searched most recently. Choose the adjacent Expression Builder button if
you want to use one or more regular expressions in your replacement string. For more information, see Using
Regular Expressions in Visual Studio.
Look in
The option chosen from the Look in drop-down list determines whether Replace in Files searches only in
currently active files or searches all files stored within certain folders. Select a search scope from the list, type a
folder path, or click the Browse (...) button to display the Choose Search Folders dialog box and choose a set of
folders to search. You can also type a path directly into the Look in box.
NOTE
If the Look in option selected causes you to search a file that you have checked out from source code control, only the
version of that file which has been downloaded to your local machine is searched.
Find options
You can expand or collapse the Find options section. The following options can be selected or cleared:
Match case
When selected, the Find Results windows will only display instances of the Find what string that are matched
both by content and by case. For example, a search for "MyObject" with Match case selected will return
"MyObject" but not "myobject" or "MYOBJECT."
Match whole word
When selected, the Find Results windows will only display instances of the Find what string that are matched in
complete words. For example, a search for "MyObject" will return "MyObject" but not "CMyObject" or "MyObjectC."
Use Regular Expressions
When this check box is selected, you can use special notations to define patterns of text in the Find what or
Replace with text boxes. For a list of these notations, see Using Regular Expressions in Visual Studio.
Look at these file types
This list indicates the types of files to search through in the Look in directories. If this field is left blank, all of the
files in the Look in directories will be searched.
Select any item in the list to enter a preconfigured search string that will find files of those particular types.
Result options
You can expand or collapse the Result options section. The following options can be selected or cleared:
Find Results 1 window
When selected, the results of the current search will replace the content of the Find Results 1 window. This
window opens automatically to display your search results. To open this window manually, select Other Windows
from the View menu and choose Find Results 1.
Find Results 2 window
When selected, the results of the current search will replace the content of the Find Results 2 window. This
window opens automatically to display your search results. To open this window manually, select Other Windows
from the View menu and choose Find Results 2.
Display file names only
When this check box is selected, the Find Results windows list the full names and paths for all files that contain the
search string. However, the results don't include the line of code where the string appears. This check box is
available for Find in Files only.
Keep modified files open after Replace All
When selected, leaves open all files in which replacements have been made, so you can undo or save the changes.
Memory constraints might limit the number of files that can remain open after a replace operation.
Cau t i on
You can use Undo only on files that remain open for editing. If this option is not selected, files that were not
already open for editing will remain closed, and no Undo option will be available in those files.
See Also
Finding and Replacing Text
Find in Files
Visual Studio Commands
Encodings and Line Breaks
10/18/2017 • 1 min to read • Edit Online
In Visual Studio you can use the File/Advanced Save Options settings to determine the type of line break
characters you want. You can also change the encoding of a file with the same settings.
NOTE
If you have certain types of development settings (Visual Basic, F#, Web Development) you may not see Advanced Save
Options on the menu. To change your settings (for example to General), open Tools / Import and Export Settings. For
more information, see Personalize the Visual Studio IDE.
You can choose to hide some code from view by collapsing a region of code so that it appears under a plus sign
(+). You expand a collapsed region by clicking the plus sign. (Or you can press CTRL + M + M to collapse a region
and then CTRL+ M + M to expand it again.) You can also collapse an outlining region by double-clicking any line in
the region on the outlining margin, which appears just to the left of the code. You can see the contents of a
collapsed region as a tooltip when you hover over the collapsed region.
Regions in the outlining margin are also highlighted when you hover over the margin with the mouse. The default
highlighting color may seem rather faint in some color configurations. You can change it in
Tools/Options/Environment/Fonts and Colors/Collapsible Region.
When you work in outlined code, you can expand the sections you want to work on, collapse them when you are
done, and then move to other sections. When you do not wish to have outlining displayed, you can use the Stop
Outlining command to remove the outline information without disturbing your underlying code.
The Undo and Redo commands on the Edit menu affect these actions. The Copy, Cut, Paste, and drag-and-drop
operations retain outlining information, but not the state of the collapsible region. For example, when you copy a
region that is collapsed, the Paste operation will paste the copied text as an expanded region.
Cau t i on
When you change an outlined region, the outlining may be lost. For example, deletions or Find and Replace
operations may erase the end of the region.
The following commands can be found on the Edit/Outlining submenu.
Toggle Outlining Expansion - Reverses the current hidden or expanded state of the
innermost outlining section when the cursor lies in a nested
collapsed section.
Toggle All Outlining (CTRL + M, CTRL + L) - Sets all regions to the same collapsed
or expanded state. If some regions are expanded and some
collapsed, then the collapsed regions are expanded.
Stop Hiding Current (CTRL + M, CTRL + U) - Removes the outlining information for
the currently selected user-defined region. Not available in
Visual Basic.
Collapse All in: <logical structures> (Visual C++) Collapses all the structures inside the function.
You can also use the Visual Studio SDK to define the text regions you want to expand or collapse. See Walkthrough:
Outlining.
Refactoring, Code Generation and Quick Actions in
Visual Studio
10/18/2017 • 1 min to read • Edit Online
Visual Studio provides a variety of tools to help you when writing code. Because the functionality of these tools is
closely tied to language syntax, each language service in Visual Studio provides its own capabilities.
Refactoring
Refactoring is the process of modifying code in order to make it easier to maintain, understand, and extend, but
without changing its behavior. For more information, see the following pages:
Refactoring (C#)
Refactoring (Visual Basic)
Writing and refactoring code (C++)
Refactoring support for F# is provided in Visual F# Power Tools, a third-party Visual Studio extension.
Code Generation
Visual Studio can help generate portions of source code for you, letting you focus on the real work. For more
information, see the following pages:
Code Generation (C#)
Code Generation (Visual Basic)
Quick Actions
Quick Actions let you easily refactor, generate, or otherwise modify code with a single action. These can be applied
using the Light Bulb icon , or pressing Ctrl + . when your cursor is on the appropriate line of code.
Quick Actions
Code Styles and Quick Actions
See Also
Visual Studio IDE
Writing Code in the Code and Text Editor
Quick Actions
10/18/2017 • 8 min to read • Edit Online
Quick Actions let you easily refactor, generate, or otherwise modify code with a single action. While there are
many Quick Actions that apply specifically to C# or Visual Basic, there are also some that apply to both C# and
Visual Basic projects. These can be applied using the Light Bulb icon , or pressing Ctrl + . when your cursor is
on the appropriate line of code.
You will see a light bulb if there is a red squiggle and Visual Studio has a suggestion for how to fix the issue. For
instance if you have an error indicated by a red squiggle, a light bulb will appear when fixes are available for that
error. For any language, third parties can provide custom diagnostics and suggestions, for example as part of an
SDK, and Visual Studio light bulbs will light up based on those rules.
To see a light bulb
1. In many cases, light bulbs spontaneously appear when you hover the mouse at the point of an error, or in
the left margin of the editor when you move the caret into a line that has an error in it. When you see a red
squiggle, you can hover over it to display the light bulb. You can also cause a light bulb to display when you
use the mouse or keyboard to go to anywhere in the line where the issue occurs.
2. Press Ctrl + . anywhere on a line to invoke the light bulb and go directly to the list of potential fixes.
...
switch(myEnum)
{
}
Enum MyEnum
Item1
Item2
Item3
End Enum
...
Using the Add Both Quick Action to fill in both missing cases and a default case will create the following:
switch(myEnum)
{
case MyEnum.Item1:
break;
case MyEnum.Item2:
break;
case MyEnum.Item3:
break;
default:
break;
}
// After
private void MyMethod()
{
}
' Before
Function MyFunction as Intger
End Function
' After
Function MyFunction as Integer
End Function
// before
int number = (int)3;
// after
int number = 3;
' Before
Dim number as Integer = CType(3, Integer)
' After
Dim number as Integer = 3
// Before
public int GetMyValue()
{
return MyValue;
}
// After
public int MyValue
{
get { return MyValue; }
}
' Before
Function GetMyValue() As Integer
Return MyValue
End Function
' After
ReadOnly Property MyValue As Integer
Get
Return MyValue
End Get
End Property
// Before
async Task<int> MyAsyncMethod()
{
return 3;
}
// After
int MyAsyncMethod()
{
return 3;
}
' Before
Async Function MyAsyncMethod() As Task(Of Integer)
Return 3
End Function
' After
Function MyAsyncMethod() As Integer
Return 3
End Function
// Before
int MyAsyncMethod()
{
return await Task.Run(...);
}
// After
async Task<int> MyAsyncMethod()
{
return await Task.Run(...);
}
' Before
Function MyAsyncMethod() as Integer
Return Await Task.Run(...)
End Function
' After
Async Function MyAsyncMethod() As Task(Of Integer)
Return Await Task.Run(...)
End Function
// using System.Diagnostics;
// After
using System.Diagnostics;
Debug.WriteLine("Hello");
' Before
Debug.WriteLine("Hello")
// After
Imports System.Diagnostics
Debug.WriteLine("Hello")
// Before
int num = 3;
string s = string.Format("My string with {0} in the middle", num);
// After
int num = 3;
string s = $"My string with {num} in the middle";
' Before
Dim num as Integer = 3
Dim s as String = String.Format("My string with {0} in the middle", num)
' After
Dim num as Integer = 3
Dim s As String = $"My string with {num} in the middle"
Generate overrides
This Quick Action enables you to create an override from a blank line in a class or struct. The Pick Members
dialog box lets you choose the members to override. (Available only in Visual Studio 2017 (version 15.3 -
Preview).)
// Before
if (obj is string s)
{
Console.WriteLine("obj is a string: " + s);
}
// Convert to switch
// After
switch (obj)
{
case string s:
Console.WriteLine("Obj is a string: " + s);
break;
case int i when i > 10:
Console.WriteLine("obj is an int greater than 10");
break;
}
' Before
If TypeOf obj Is String s Then
Console.WriteLine("obj is a string: " + s)
Else If TypeOf obj Is Integer i And i > 10 Then
Console.WriteLine("obj is an int greater than 10")
End If
' After
Select Case obj
Case String s
Console.WriteLine("Obj is a string: " + s)
Exit Sub
Case Integer i when i > 10
Console.WriteLine("obj is an int greater than 10")
Exit Sub
End Select
See Also
Code Styles and Quick Actions
Code Styles and Quick Actions
10/18/2017 • 1 min to read • Edit Online
Code style preferences can be set for your C# and Visual Basic projects by opening the Tools > Options window,
and then selecting Text Editor > C# / Basic > Code Style > General. Options set in this window are applicable to
the local machine. Each item in the list will show a preview of the preference when selected, as shown below.
For each item, you can set the Preference and Severity using the drop downs on each line. Severity can be set to
None, Suggestion, Warning, or Error, and Visual Studio will behave appropriately. If you want to use Quick
Actions with these code styles to automatically rewrite code to the preferred style, ensure that the setting is set to
something other than None so the light bulb icon will appear when the non-preferred styles are used. These
preferences can then can be applied by clicking the Light Bulb icon or pressing Ctrl + . when your cursor is on the
appropriate line of code.
Code Style settings for .NET can also be managed with an EditorConfig file. In this case, the settings selected in the
Options window will be the fallback settings, with the EditorConfig file taking precedence. You can use this file to
enforce and configure the coding style for your entire repo or team.
See Also
Quick Actions
.NET coding convention settings for EditorConfig
10/19/2017 • 29 min to read • Edit Online
You can define and maintain consistent code style in your codebase with the use of an EditorConfig file.
EditorConfig includes several core formatting properties, such as indent_style and indent_size . In Visual Studio,
.NET coding conventions settings can also be configured using an EditorConfig file. EditorConfig files allow you to
enable or disable individual .NET coding conventions, and to configure the degree to which you want the
convention enforced via a severity level. To learn more about how to use EditorConfig to enforce consistency in
your codebase, read Create portable custom editor options. You can also look at the .NET Compiler Platform's
.editorconfig file as an example.
There are three supported .NET coding convention categories:
Language Conventions
Rules pertaining to the C# or Visual Basic language. For example, you can specify rules around using var or
explicit types when defining variables, or preferring expression-bodied members.
Formatting Conventions
Rules regarding the layout and structure of your code in order to make it easier to read. For example, you can
specify rules around Allman braces, or preferring spaces in control blocks.
Naming Conventions
Rules regarding the naming of code elements. For example, you can specify that async methods must end in
"Async".
Language conventions
Rules for language conventions have the following format:
options_name = false|true : none|suggestion|warning|error
For each language convention rule, you must specify either true (prefer this style) or false (do not prefer this style),
and a severity. The severity specifies the level of enforcement for that style.
The following table lists the possible severity values and their effects:
SEVERITY EFFECT
none or silent Do not show anything to the user when this rule is violated.
Code generation features will generate code in this style,
however.
dotnet_style_qualification_for_field
When this rule is set to true, prefer fields to be prefaced with this. in C# or Me. in Visual Basic.
When this rule is set to false, prefer fields not to be prefaced with this. or Me. .
Code examples:
// dotnet_style_qualification_for_field = true
this.capacity = 0;
// dotnet_style_qualification_for_field = false
capacity = 0;
dotnet_style_qualification_for_property
When this rule is set to true, prefer properties to be prefaced with this. in C# or Me. in Visual Basic.
When this rule is set to false, prefer properties not to be prefaced with this. or Me. .
Code examples:
// dotnet_style_qualification_for_property = true
this.ID = 0;
// dotnet_style_qualification_for_property = false
ID = 0;
dotnet_style_qualification_for_method
When this rule is set to true, prefer methods to be prefaced with this. in C# or Me. in Visual Basic.
When this rule is set to false, prefer methods not to be prefaced with this. or Me. .
Code examples:
// dotnet_style_qualification_for_method = true
this.Display();
// dotnet_style_qualification_for_method = false
Display();
dotnet_style_qualification_for_event
When this rule is set to true, prefer events to be prefaced with this. in C# or Me. in Visual Basic.
When this rule is set to false, prefer events not to be prefaced with this. or Me. .
Code examples:
// dotnet_style_qualification_for_event = true
this.Elapsed += Handler;
// dotnet_style_qualification_for_event = false
Elapsed += Handler;
dotnet_style_predefin IDE0012 and C# and Visual Basic true:none Visual Studio 2017
ed_type_for_locals_par IDE0014 RTW
ameters_members
dotnet_style_predefin IDE0013 and C# and Visual Basic true:none Visual Studio 2017
ed_type_for_member_ IDE0015 RTW
access
dotnet_style_predefined_type_for_locals_parameters_members
When this rule is set to true, prefer the language keyword for local variables, method parameters, and class
members, instead of the type name, for types that have a keyword to represent them.
When this rule is set to false, prefer the type name for local variables, method parameters, and class members,
instead of the language keyword.
Code examples:
// dotnet_style_predefined_type_for_locals_parameters_members = true
private int _member;
// dotnet_style_predefined_type_for_locals_parameters_members = false
private Int32 _member;
dotnet_style_predefined_type_for_member_access
When this rule is set to true, prefer the language keyword for member access expressions, instead of the type
name, for types that have a keyword to represent them.
When this rule is set to false, prefer the type name for member access expressions, instead of the language
keyword.
Code examples:
// dotnet_style_predefined_type_for_member_access = true
var local = int.MaxValue;
// dotnet_style_predefined_type_for_member_access = false
var local = Int32.MaxValue;
Expression-level preferences
The style rules in this section concern expression-level preferences, including the use of object initializers, collection
initializers, explicit tuple names, null coalescing expressions versus ternary operators, and the null-conditional
operator.
The following table shows the rule names, rule IDs, applicable programming languages, default values, and first
supported version of Visual Studio:
dotnet_style_object_initializer
When this rule is set to true, prefer objects to be initialized using object initializers when possible.
When this rule is set to false, prefer objects to not be initialized using object initializers.
Code examples:
// dotnet_style_object_initializer = true
var c = new Customer() { Age = 21 };
// dotnet_style_object_initializer = false
var c = new Customer();
c.Age = 21;
dotnet_style_collection_initializer
When this rule is set to true, prefer collections to be initialized using collection initializers when possible.
When this rule is set to false, prefer collections to not be initialized using collection initializers.
Code examples:
// dotnet_style_collection_initializer = true
var list = new List<int> { 1, 2, 3 };
// dotnet_style_collection_initializer = false
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
dotnet_style_explicit_tuple_names
When this rule is set to true, prefer tuple names to ItemX properties.
When this rule is set to false, prefer ItemX properties to tuple names.
Code examples:
// dotnet_style_explicit_tuple_names = true
(string name, int age) customer = GetCustomer();
var name = customer.name;
// dotnet_style_explicit_tuple_names = false
(string name, int age) customer = GetCustomer();
var name = customer.Item1;
dotnet_style_coalesce_expression
When this rule is set to true, prefer null coalescing expressions to ternary operator checking.
When this rule is set to false, prefer ternary operator checking to null coalescing expressions.
Code examples:
// dotnet_style_coalesce_expression = true
var v = x ?? y;
// dotnet_style_coalesce_expression = false
var v = x != null ? x : y; // or
var v = x == null ? y : x;
' dotnet_style_coalesce_expression = true
Dim v = If(x, y)
dotnet_style_null_propagation
When this rule is set to true, prefer to use null-conditional operator when possible.
When this rule is set to false, prefer to use ternary null checking where possible.
Code examples:
// dotnet_style_null_propagation = true
var v = o?.ToString();
// dotnet_style_null_propagation = false
var v = o == null ? null : o.ToString(); // or
var v = o != null ? o.String() : null;
csharp_style_var_for_built_in_types
When this rule is set to true, prefer var is used to declare variables with built-in system types such as int .
When this rule is set to false, prefer explicit type over var to declare variables with built-in system types such as
int .
Code examples:
// csharp_style_var_for_built_in_types = true
var x = 5;
// csharp_style_var_for_built_in_types = false
int x = 5;
csharp_style_var_when_type_is_apparent
When this rule is set to true, prefer var when the type is already mentioned on the right-hand side of a
declaration expression.
When this rule is set to false, prefer explicit type over var when the type is already mentioned on the right-hand
side of a declaration expression.
Code examples:
// csharp_style_var_when_type_is_apparent = true
var obj = new Customer();
// csharp_style_var_when_type_is_apparent = false
Customer obj = new Customer();
csharp_style_var_elsewhere
When this rule is set to true, prefer var over explicit type in all cases, unless overridden by another code style rule.
When this rule is set to false, prefer explicit type over var in all cases, unless overridden by another code style
rule.
Code examples:
// csharp_style_var_elsewhere = true
var f = this.Init();
// csharp_style_var_elsewhere = false
bool f = this.Init();
The style rules in this section concern the use of expression-bodied members when the logic consists of a single
expression. This rule can be applied to methods, constructors, operators, properties, indexers, and accessors.
The following table shows the rule names, rule IDs, applicable language versions, default values, and first supported
version of Visual Studio:
csharp_style_expression_bodied_methods
When this rule is set to true, prefer expression-bodied members for methods.
When this rule is set to false, do not prefer expression-bodied members for methods.
Code examples:
// csharp_style_expression_bodied_methods = true
public int GetAge() => this.Age;
// csharp_style_expression_bodied_methods = false
public int GetAge() { return this.Age; }
csharp_style_expression_bodied_constructors
When this rule is set to true, prefer expression-bodied members for constructors.
When this rule is set to false, do not prefer expression-bodied members for constructors.
Code examples:
// csharp_style_expression_bodied_constructors = true
public Customer(int age) => Age = age;
// csharp_style_expression_bodied_constructors = false
public Customer(int age) { Age = age; }
csharp_style_expression_bodied_operators
When this rule is set to true, prefer expression-bodied members for operators.
When this rule is set to false, do not prefer expression-bodied members for operators.
Code examples:
// csharp_style_expression_bodied_operators = true
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
=> new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
// csharp_style_expression_bodied_operators = false
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
{ return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); }
csharp_style_expression_bodied_properties
When this rule is set to true, prefer expression-bodied members for properties.
When this rule is set to false, do not prefer expression-bodied members for properties.
Code examples:
// csharp_style_expression_bodied_properties = true
public int Age => _age;
// csharp_style_expression_bodied_properties = false
public int Age { get { return _age; }}
csharp_style_expression_bodied_indexers
When this rule is set to true, prefer expression-bodied members for indexers.
When this rule is set to false, do not prefer expression-bodied members for indexers.
Code examples:
// csharp_style_expression_bodied_indexers = true
public T this[int i] => _value[i];
// csharp_style_expression_bodied_indexers = false
public T this[int i] { get { return _values[i]; } }
csharp_style_expression_bodied_accessors
When this rule is set to true, prefer expression-bodied members for accessors.
When this rule is set to false, do not prefer expression-bodied members for accessors.
Code examples:
// csharp_style_expression_bodied_accessors = true
public int Age { get => _age; set => _age = value; }
// csharp_style_expression_bodied_accessors = false
public int Age { get { return _age; } set { _age = value; } }
Pattern matching
The style rules in this section concern the use of pattern matching in C#.
The following table shows the rule names, rule IDs, applicable language versions, default values, and first supported
version of Visual Studio:
csharp_style_pattern_matching_over_is_with_cast_check
When this rule is set to true, prefer pattern matching instead of is expressions with type casts.
When this rule is set to false, prefer is expressions with type casts instead of pattern matching.
Code examples:
// csharp_style_pattern_matching_over_is_with_cast_check = true
if (o is int i) {...}
// csharp_style_pattern_matching_over_is_with_cast_check = false
if (o is int) {var i = (int)o; ... }
csharp_style_pattern_matching_over_as_with_null_check
When this rule is set to true, prefer pattern matching instead of as expressions with null checks to determine if
something is of a particular type.
When this rule is set to false, prefer as expressions with null checks instead of pattern matching to determine if
something is of a particular type.
Code examples:
// csharp_style_pattern_matching_over_as_with_null_check = true
if (o is string s) {...}
// csharp_style_pattern_matching_over_as_with_null_check = false
var s = o as string;
if (s != null) {...}
csharp_style_inlined_variable_declaration
When this rule is set to true, prefer out variables to be declared inline in the argument list of a method call when
possible.
When this rule is set to false, prefer out variables to be declared before the method call.
Code examples:
// csharp_style_inlined_variable_declaration = true
if (int.TryParse(value, out int i) {...}
// csharp_style_inlined_variable_declaration = fale
int i;
if (int.TryParse(value, out i) {...}
Expression-level preferences
This style rule concerns using the default literal for default value expressions when the compiler can infer the type
of the expression.
The following table shows the rule name, rule ID, applicable language versions, default values, and first supported
version of Visual Studio:
csharp_prefer_simple_default_expression
When this rule is set to true, prefer default over default(T) .
When this rule is set to false, prefer default(T) over default .
Code examples:
// csharp_prefer_simple_default_expression = true
void DoWork(CancellationToken cancellationToken = default) { ... }
// csharp_prefer_simple_default_expression = false
void DoWork(CancellationToken cancellationToken = default(CancellationToken)) { ... }
csharp_style_throw_expression
When this rule is set to true, prefer to use throw expressions instead of throw statements.
When this rule is set to false, prefer to use throw statements instead of throw expressions.
Code examples:
// csharp_style_throw_expression = true
this.s = s ?? throw new ArgumentNullException(nameof(s));
// csharp_style_throw_expression = false
if (s == null) { throw new ArgumentNullException(nameof(s)); }
this.s = s;
csharp_style_conditional_delegate_call
When this rule is set to true, prefer to use the conditional coalescing operator ( ?. ) when invoking a lambda
expression, instead of performing a null check.
When this rule is set to false, prefer to perform a null check before invoking a lambda expression, instead of using
the conditional coalescing operator ( ?. ).
Code examples:
// csharp_style_conditional_delegate_call = true
func?.Invoke(args);
// csharp_style_conditional_delegate_call = false
if (func != null) { func(args); }
csharp_prefer_braces
When this rule is set to true, prefer curly braces even for one line of code.
When this rule is set to false, prefer no curly braces if allowed.
Code examples:
// csharp_prefer_braces = true
if (test) { this.Display(); }
// csharp_prefer_braces = false
if (test) this.Display();
Formatting conventions
Most of the rules for formatting conventions have the following format:
rule_name = false|true
You specify either true (prefer this style) or false (do not prefer this style). You do not specify a severity. For a few
rules, instead of true or false, you specify other values to describe when and where to apply the rule.
The following list shows the formatting convention rules available in Visual Studio:
.NET Formatting Settings
Organize Usings
dotnet_sort_system_directives_first
C# Formatting Settings
Newline Options
csharp_new_line_before_open_brace
csharp_new_line_before_else
csharp_new_line_before_catch
csharp_new_line_before_finally
csharp_new_line_before_members_in_object_initializers
csharp_new_line_before_members_in_anonymous_types
csharp_new_line_between_query_expression_clauses
Indentation Options
csharp_indent_case_contents
csharp_indent_switch_labels
csharp_indent_labels
Spacing Options
csharp_space_after_cast
csharp_space_after_keywords_in_control_flow_statements
csharp_space_between_method_declaration_parameter_list_parentheses
csharp_space_between_method_call_parameter_list_parentheses
csharp_space_between_parentheses
Wrapping Options
csharp_preserve_single_line_statements
csharp_preserve_single_line_blocks
.NET formatting settings
The formatting rules in this section are applicable to C# and Visual Basic.
Organize usings
This formatting rule concerns the placement of System.* using directives with respect to other using directives.
The following table shows the rule name, applicable languages, default value, and first supported version of Visual
Studio:
dotnet_sort_system_directives_first
When this rule is set to true, sort System.* using directives alphabetically, and place them before other usings.
When this rule is set to false, do not place System.* using directives before other using directives.
Code examples:
// dotnet_sort_system_directives_first = true
using System.Collections.Generic;
using System.Threading.Tasks;
using Octokit;
// dotnet_sort_system_directives_first = false
using System.Collections.Generic;
using Octokit;
using System.Threading.Tasks;
Newline Options
These formatting rules concern the use of new lines to format code.
The following table shows the "new line" rule names, applicable languages, default values, and first supported
version of Visual Studio:
RULE NAME APPLICABLE LANGUAGES VISUAL STUDIO DEFAULT SUPPORTED VERSION
csharp_new_line_before_open_brace
This rule concerns whether an open brace { should be placed on the same line as the preceding code, or on a new
line. For this rule, you do not specify true or false. Instead you specify all, none, or one or more code elements
such as methods or properties, to define when this rule should be applied. The complete list of allowable values is
shown in the following table:
VALUE DESCRIPTION
accessors, anonymous_methods, anonymous_types, Require braces to be on a new line for the specified code
control_blocks, events, indexers, lambdas, local_functions, elements (also known as "Allman" style)
methods, object_collection, properties, types.
(For multiple kinds, separate with ',').
Code examples:
// csharp_new_line_before_open_brace = all
void MyMethod()
{
if (...)
{
...
}
}
// csharp_new_line_before_open_brace = none
void MyMethod() {
if (...) {
...
}
}
csharp_new_line_before_else
When this rule is set to true, place else statements on a new line.
When this rule is set to false, place else statements on the same line.
Code examples:
// csharp_new_line_before_else = true
if (...) {
...
}
else {
...
}
// csharp_new_line_before_else = false
if (...) {
...
} else {
...
}
csharp_new_line_before_catch
When this rule is set to true, place catch statements on a new line.
When this rule is set to false, place catch statements on the same line.
Code examples:
// csharp_new_line_before_catch = true
try {
...
}
catch (Exception e) {
...
}
// csharp_new_line_before_catch = false
try {
...
} catch (Exception e) {
...
}
csharp_new_line_before_finally
When this rule is set to true, require finally statements to be on a new line after the closing brace.
When this rule is set to false, require finally statements to be on the same line as the closing brace.
Code examples:
// csharp_new_line_before_finally = true
try {
...
}
catch (Exception e) {
...
}
finally {
...
}
// csharp_new_line_before_finally = false
try {
...
} catch (Exception e) {
...
} finally {
...
}
csharp_new_line_before_members_in_object_initializers
When this rule is set to true, require members of object intializers to be on separate lines.
When this rule is set to false, require members of object initializers to be on the same line.
Code examples:
// csharp_new_line_before_members_in_object_initializers = true
var z = new B()
{
A = 3,
B = 4
}
// csharp_new_line_before_members_in_object_initializers = false
var z = new B()
{
A = 3, B = 4
}
csharp_new_line_before_members_in_anonymous_types
When this rule is set to true, require members of anonymous types to be on separate lines.
When this rule is set to false, require members of anonymous types to be on the same line.
Code examples:
// csharp_new_line_before_members_in_anonymous_types = true
var z = new
{
A = 3,
B = 4
}
// csharp_new_line_before_members_in_anonymous_types = false
var z = new
{
A = 3, B = 4
}
csharp_new_line_between_query_expression_clauses
When this rule is set to true, require elements of query expression clauses to be on separate lines.
When this rule is set to false, require elements of query expression clauses to be on the same line.
Code examples:
// csharp_new_line_between_query_expression_clauses = true
var q = from a in e
from b in e
select a * b;
// csharp_new_line_between_query_expression_clauses = false
var q = from a in e from b in e
select a * b;
Indentation options
These formatting rules concern the use of indentation to format code.
The following table shows the rule names, applicable languages, default values, and first supported version of
Visual Studio:
csharp_indent_case_contents
When this rule is set to true, indent switch case contents.
When this rule is set to false, do not indent switch case contents.
Code examples:
// csharp_indent_case_contents = true
switch(c) {
case Color.Red:
Console.WriteLine("The color is red");
break;
case Color.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
// csharp_indent_case_contents = false
switch(c) {
case Color.Red:
Console.WriteLine("The color is red");
break;
case Color.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
csharp_indent_switch_labels
When this rule is set to true, indent switch labels.
When this rule is set to false, do not indent switch labels.
Code examples:
// csharp_indent_switch_labels = true
switch(c) {
case Color.Red:
Console.WriteLine("The color is red");
break;
case Color.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
// csharp_indent_switch_labels = false
switch(c) {
case Color.Red:
Console.WriteLine("The color is red");
break;
case Color.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
csharp_indent_labels
This rule does not accept a true or false value; instead it accepts a value from the following table:
VALUE DESCRIPTION
one_less_than_current Labels are placed at one less indent to the current context
no_change Labels are placed at the same indent as the current context
Code examples:
// csharp_indent_labels= flush_left
class C
{
private string MyMethod(...)
{
if (...) {
goto error;
}
error:
throw new Exception(...);
}
}
// csharp_indent_labels = one_less_than_current
class C
{
private string MyMethod(...)
{
if (...) {
goto error;
}
error:
throw new Exception(...);
}
}
// csharp_indent_labels= no_change
class C
{
private string MyMethod(...)
{
if (...) {
goto error;
}
error:
throw new Exception(...);
}
}
Spacing Options
These formatting rules concern the use of space characters to format code.
The following table shows the rule names, applicable languages, default values, and first supported version of
Visual Studio:
csharp_space_after_cast
When this rule is set to true, require a space between a cast and the value.
When this rule is set to false, require no space between the cast and the value.
Code examples:
// csharp_space_after_cast = true
int y = (int) x;
// csharp_space_after_cast = false
int y = (int)x;
csharp_space_after_keywords_in_control_flow_statements
When this rule is set to true, require a space after a keyword in a control flow statement such as a for loop.
When this rule is set to false, require no space after a keyword in a control flow statement such as a for loop.
Code examples:
// csharp_space_after_keywords_in_control_flow_statements = true
for (int i;i<x;i++) { ... }
// csharp_space_after_keywords_in_control_flow_statements = false
for(int i;i<x;i++) { ... }
csharp_space_between_method_declaration_parameter_list_parentheses
When this rule is set to true, place a space character after the opening parenthesis and before the closing
parenthesis of a method declaration parameter list.
When this rule is set to false, do not place space characters after the opening parenthesis and before the closing
parenthesis of a method declaration parameter list.
Code examples:
// csharp_space_between_method_declaration_parameter_list_parentheses = true
void Bark( int x ) { ... }
// csharp_space_between_method_declaration_parameter_list_parentheses = false
void Bark(int x) { ... }
csharp_space_between_method_call_parameter_list_parentheses
When this rule is set to true, place a space character after the opening parenthesis and before the closing
parenthesis of a method call.
When this rule is set to false, do not place space characters after the opening parenthesis and before the closing
parenthesis of a method call.
Code examples:
// csharp_space_between_method_call_parameter_list_parentheses = true
MyMethod( argument );
// csharp_space_between_method_call_parameter_list_parentheses = false
MyMethod(argument);
csharp_space_between_parentheses
This rule does not accept a true or false value; instead it accepts a value from the following table:
VALUE DESCRIPTION
Code examples:
// csharp_space_between_parentheses = control_flow_statements
for( int i;i<x;i++ ) { ... }
// csharp_space_between_parentheses = expressions
var z = ( x * y ) - ( ( y - x ) * 3);
// csharp_space_between_parentheses = type_casts
int y = ( int )x;
Wrapping options
These formatting rules concern the use of single lines versus separate lines for statements and code blocks.
The following table shows the rule names, applicable languages, default values, and first supported version of
Visual Studio:
csharp_preserve_single_line_statements
When this rule is set to true, leave statements and member declarations on the same line.
When this rule is set to false, leave statements and member declarations on different lines.
Code examples:
//csharp_preserve_single_line_statements = true
int i = 0; string name = "John";
//csharp_preserve_single_line_statements = false
int i = 0;
string name = "John";
csharp_preserve_single_line_blocks
When this rule is set to true, leave code block on single line.
When this rule is set to false, leave code block on separate lines.
Code examples:
//csharp_preserve_single_line_blocks = true
public int Foo { get; set; }
//csharp_preserve_single_line_blocks = false
public int MyProperty
{
get; set;
}
Naming conventions
Naming conventions concern the naming of code elements such as classes, properties, and methods. For example,
you can specify that asynchronous methods must end in "Async". Naming conventions should be ordered from
most-specific to least-specific. The first rule encountered that can be applied is the only rule that is applied.
For each naming convention rule, identified by namingRuleTitle, you must specify the symbols it applies to, a
naming style, and a severity:
dotnet_naming_rule.<namingRuleTitle>.symbols = <symbolTitle>
dotnet_naming_rule.<namingRuleTitle>.style = <styleTitle>
dotnet_naming_rule.<namingRuleTitle>.severity = none|suggestion|warning|error
Symbols
Identify a group of symbols to apply a naming rule to with this property:
dotnet_naming_rule.<namingRuleTitle>.symbols = <symbolTitle> . Specify which kind of symbols, which modifiers,
and which accessibility levels are included in the group using the following properties:
Style
Identify the naming style to apply to a group of symbols with this property:
dotnet_naming_rule.<namingRuleTitle>.style = <styleTitle> .
Specify the naming style using one or more of the following properties:
NOTE
You must specify a capitalization style as part of your naming style, otherwise your naming style will be ignored.
Severity
Identify the severity level for a naming rule with this property: dotnet_naming_rule.<namingRuleTitle>.severity .
The following table shows the severity value options:
SEVERITY EFFECT
none or silent When this style is not being followed, do not show anything
to the user; however, code generation features generate new
code in this style.
suggestion When this style is not being followed, show it to the user as a
suggestion (underlying dots on the first two characters). It has
no effect at compile time.
SEVERITY EFFECT
error When this style is not being followed, show a compiler error.
dotnet_naming_symbols.any_async_methods.applicable_kinds = method
dotnet_naming_symbols.any_async_methods.applicable_accessibilities = *
dotnet_naming_symbols.any_async_methods.required_modifiers = async
dotnet_naming_style.end_in_async.required_suffix = Async
dotnet_naming_style.end_in_async.capitalization = pascal_case
See also
Quick Actions
Create portable custom editor options
.NET Compiler Platform's .editorconfig file
Preview Changes
10/18/2017 • 1 min to read • Edit Online
When using various Quick Actions or Refactoring tools in Visual Studio, it is often possible to preview changes that
are going to be made to your project prior to accepting them. The Preview Changes window is where this is done.
For example, here is the Preview Changes window showing what will be changed during a Rename refactor in a
C# project:
The top half of the window shows the specific lines that will be changed, each with a checkbox. You can check or
uncheck each checkbox if you want to selectively apply the refactoring to only specific lines.
The bottom half of the window shows the formatted code from the project that will be changed, with the affected
areas highlighted. Selecting the specific line in the top half of the window will highlight the corresponding line in
the bottom half. This allows you to quickly skip to the appropriate line and see the surrounding code.
After reviewing the changes, click the Apply button to commit those changes, or click the Cancel button to leave
things as they were.
See Also
Refactoring in Visual Studio
Productivity Tips for Visual Studio
10/18/2017 • 8 min to read • Edit Online
By following these tips, you can more quickly and efficiently write, navigate, and debug your code in Visual Studio.
For more information about common keyboard shortcuts, see Tips and Tricks. For a more complete list, see
Identifying and Customizing Keyboard Shortcuts and Default Keyboard Shortcuts.
This topic includes the following sections:
Accessing Visual Studio Tools
Writing Code
Navigating Within Your Code
Finding Items Faster
Debugging Code
Managing Files, Toolbars, and Windows
Writing Code
Write code more quickly by using the following features.
Use sample applications. You can speed up application development by downloading and installing
sample applications from the MSDN Code Gallery. You can also learn a particular technology or
programming concept by downloading and exploring a Sample Pack for that area.
Use IntelliSense. As you enter code in the editor, IntelliSense information, such as List Members,
Parameter Info, Quick Info, Signature Help, and Complete Word, appears. These features support fuzzy
matching of text; for example, the results lists for List Members includes not only entries that start with the
characters that you have entered but also entries that contain the character combination anywhere in their
names. For more information, see Using IntelliSense.
Change auto-insertion of IntelliSense options as you enter code. By switching IntelliSense to
suggestion mode, you can specify that IntelliSense options are inserted only if you explicitly choose them.
To enable suggestion mode, choose the Ctrl + Alt + Spacebar keys, or, on the menu bar, choose Edit,
IntelliSense, Toggle Completion Mode.
Use code snippets. You can use built-in snippets or create your own snippets.
To insert a snippet, on the menu bar, choose Edit, IntelliSense, Insert Snippet or open the shortcut menu
in a file and choose Insert Snippet. For more information, see Code Snippets.
Fix code errors inline. Quick Actions let you easily refactor, generate, or otherwise modify code with a
single action. These actions can be applied using the Light Bulb icon , or by pressing Alt + Enter or Ctrl
+ . when your cursor is on the appropriate line of code. See Quick Actions for more information.
Show and edit the definition of a code element. You can quickly show and edit the module in which a
code element, such as a member, a variable, or a local, is defined.
To open a definition in a pop-up window, highlight the element and then choose the Alt+F12 keys, or open
the shortcut menu for the element and then choose Peek Definition. To open a definition in a separate
code window, open the shortcut menu for the element, and then choose Go to Definition.
Quick Launch displays links to the New Project dialog box, the Add New Item dialog box, and the
Projects and Solutions page in the Options dialog box, among others. Quick Launch results can also include
project files and tool windows.
Debugging Code
Debugging can consume a lot of time, but the following tips can help you speed up the process.
Test the same page, application, or site in different browsers. As you debug your code, you can easily
switch among the installed web browsers, including Page Inspector (Visual Studio), without having to open
the Browse With dialog box. You can use the Debug Target list, which is on the Standard toolbar next to
the Start Debugging button, to quickly verify which browser you're using as you debug or view pages.
Set temporary breakpoints. You can create a temporary breakpoint in the current line of code and start
the debugger simultaneously. When you hit that line of code, the debugger enters break mode. For more
information, see Navigating through Code with the Debugger.
To use this feature, choose the Ctrl + F10 keys, or open the shortcut menu for the line of code on which you
want to break, and then choose Run To Cursor.
Move the execution point during debugging. You can move the current execution point to a different
section of code and then restart debugging from that point. This technique is useful if you want to debug a
section of code without having to recreate all of the steps that are required to reach that section. For more
information, see Navigating through Code with the Debugger.
To move the execution point, drag the yellow arrowhead to a location where you want to set the next
statement in the same source file, and then choose the F5 key to continue debugging.
Capture value information for variables. You can add a DataTip to a variable in your code and pin it so
that you can access the last known value for the variable after debugging has finished. For more
information, see View data values in Data Tips.
To add a DataTip, the debugger must be in break mode. Place the cursor on the variable, and then choose
the pin button on the DataTip that appears. When debugging is stopped, a blue pin icon appears in the
source file next to the line of code that contains the variable. If you point to the blue pin, the value of the
variable from the most recent debugging session appears.
Clear the Immediate window. You can erase the contents of the Immediate Window at design time by
entering >cls or >Edit.ClearAll
For more information about additional commands, see Visual Studio Command Aliases.
See Also
Default Keyboard Shortcuts for Frequently Used Commands
How to: Customize Menus and Toolbars
Walkthrough: Create a Simple Application
Accessibility Tips and Tricks
Tips and Tricks for Visual Studio
10/18/2017 • 2 min to read • Edit Online
You can navigate in Visual Studio 2013 more easily by using the shortcuts in this topic. This topic is only a subset
of the available keyboard shortcuts. For a more complete list, see Default Keyboard Shortcuts in Visual Studio. For
information about how to optimize Visual Studio for accessibility, see Accessibility Tips and Tricks.
Window Management
Window Shortcuts
Place Focus in Search box in any tool window Alt+` when the tool window has focus
Editor Find
Code Editor
Navigate To Ctrl+,
Go To Definition F12
Toggle between the code editor window and the Peek Shift+Esc
Definition window
Toolbars
Debugging
Start Debugging F5
See Also
Visual Studio Blog
Visual Studio Tips and Tricks Blog
Visual Studio Toolbox on Channel 9
Visual Studio UserVoice
Visual Studio Connect Bugs
Identifying and Customizing Keyboard Shortcuts in
Visual Studio
10/18/2017 • 4 min to read • Edit Online
You can identify keyboard shortcuts for Visual Studio commands, customize those shortcuts, and export them for
others to use. Many shortcuts always invoke the same commands, but the behavior of a shortcut can vary based
on the following conditions:
Which default environment settings you chose the first time that you ran Visual Studio (for example,
General Development or Visual C#).
Whether you've customized the shortcut's behavior.
Which context you're in when you choose the shortcut. For example, the F2 shortcut invokes the
Edit.EditCell command if you're using the Settings Designer and the File.Rename command if you're using
Team Explorer.
Regardless of settings, customization, and context, you can always find and change a keyboard shortcut in
the Options dialog box. You can also look up the default keyboard shortcuts for several dozen commands
in Default Keyboard Shortcuts for Frequently Used Commands, and you can find a complete list of all
default shortcuts (based on the General Development Settings) in Default Keyboard Shortcuts.
In this topic
Identifying a keyboard shortcut
Customizing a keyboard shortcut
Sharing custom keyboard shortcuts
If a shortcut is assigned to a command in the Global context and no other contexts, that shortcut will always
invoke that command. But a shortcut can be assigned to one command in the Global context and a different
command in a specific context. If you use such a shortcut when you're in the specific context, the shortcut
invokes the command for the specific context, not the Global context.
NOTE
Your settings and edition of Visual Studio might change the names and locations of menu commands and the options that
appear in dialog boxes. This topic is based on the General Development Settings.
NOTE
You can't assign the following keys as part of a keyboard shortcut in Global: Print Scrn/Sys Rq, Scroll Lock,
Pause/Break, Tab, Caps Lock, Insert, Home, End, Page Up, Page Down, the Windows logo key, the Application key,
any of the Arrow keys, or Enter; Num Lock, Delete, or Clear on the numeric keypad; or Ctrl+Alt+Delete.
6. In the Press shortcut key(s) box, enter the shortcut that you want to use.
NOTE
You can create a shortcut that combines a letter with the Alt key, the Ctrl key, or both. You can also create a
shortcut that combines the Shift key and a letter with the Alt key, the Ctrl key, or both.
If a shortcut is already assigned to another command, it appears in the Shortcut currently used by box. In
that case, choose the Backspace key to delete that shortcut before you try a different one.
NOTE
If you specify a different shortcut for a command, choose the Assign button, and then choose the Cancel button,
the dialog box closes, but the change isn't reverted.
See Also
Accessibility Features of Visual Studio
Default Keyboard Shortcuts for Frequently Used
Commands in Visual Studio
10/18/2017 • 2 min to read • Edit Online
You can access frequently used commands in Visual Studio by choosing these default keyboard shortcuts. For a
complete list of commands that have default shortcuts, see Default Keyboard Shortcuts.
NOTE
You can look up the shortcut for any command by opening the Options dialog box, expanding the Environment node, and
then choosing Keyboard.
In this topic
Build
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Debug
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
or Shift+F9 [Global]
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Debug.Start F5 [Global]
Debug.ToggleBreakpoint F9 [Global]
Edit
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
or Ctrl+Insert [Global]
or Shift+Delete [Global]
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Edit.FindNext F3 [Global]
Edit.GoToDefinition F12
Edit.GoToNextLocation F8 [Global]
or Shift+Insert [Global]
or Shift+Alt+Backspace [Global]
or Ctrl+Shift+Z [Global]
or Alt+Backspace [Global]
File
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Project
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Refactor
COMMAND KEYBOARD SHORTCUT [CONTEXT]
Tools
COMMAND KEYBOARD SHORTCUT [CONTEXT]
View
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
View.EditLabel F2 [Global]
or Ctrl+\, E [Global]
View.PropertiesWindow F4
or F7 [Settings Designer]
Window
COMMANDS KEYBOARD SHORTCUTS [CONTEXTS]
Window.NextSplitPane F6 [Global]
Default Keyboard Shortcuts in Visual Studio
10/18/2017 • 13 min to read • Edit Online
For more information about keyboard accessibility, see Accessibility Tips and Tricks and How to: Use the Keyboard
Exclusively.
You can access a variety of commands and windows in Visual Studio by choosing the appropriate keyboard
shortcut. This topic lists the default shortcuts for the General Development profile, which you might have chosen
when you installed Visual Studio. No matter which profile you chose, you can identify the shortcut for a command
by opening the Options dialog box, expanding the Environment node, and then choosing Keyboard. You can
also customize your shortcuts by assigning a different shortcut to any given command.
For a list of common keyboard shortcuts and other productivity information, see Default Keyboard Shortcuts for
Frequently Used Commands in Visual Studio, Tips and Tricks, and Productivity Tips.
The sections in the following table include commands that are global in that you can access them from anywhere
in Visual Studio by using keyboard shortcuts:
Architecture Editor Context Menus Project and Solution Context Test Explorer
Menus
Debugger Context Menus Other Context Menus Team Foundation Context Azure
Menus
Diagnostics Hub
Each section in the following table includes commands for which the keyboard shortcuts are specific to the context
for which the section is named.
ADO.NET Entity Data Model Layer Diagram Settings Designer VC Image Editor
Designer
Coded UI Test Editor Merge Editor Window Team Explorer View Designer
DataSet Editor Microsoft SQL Server Data Team Foundation Build Visual Studio
Tools, Schema Compare Detail Editor
Difference Viewer Microsoft SQL Server Data Test Explorer Windows Forms Designer
Tools, Table Designer
DOM Explorer Microsoft SQL Server Data Text Editor Work Item Editor
Tools, T-SQL Editor
F# Interactive Microsoft SQL Server Data UML Activity Diagram Work Item Query View
Tools, T-SQL PDW Editor
Graph Document Editor Page Inspector UML Class Diagram Work Item Results View
HTML Editor Query Results UML Use Case Diagram XAML UI Designer
HTML Editor Design View Report Designer VC Accelerator Editor XML (Text) Editor
HTML Editor Source View Sequence Diagram VC Dialog Editor XML Schema Designer
Global
Analyze
COMMANDS KEYBOARD SHORTCUTS
Analyze.NavigateBackward Shift+Alt+3
Analyze.NavigateForward Shift+Alt+4
Architecture
COMMANDS KEYBOARD SHORTCUTS
Build
COMMANDS KEYBOARD SHORTCUTS
Build.BuildSolution Ctrl+Shift+B
Build.Cancel Ctrl+Break
Build.Compile Ctrl+F7
Build.RunCodeAnalysisonSolution Alt+F11
ClassViewContextMenus.ClassViewMultiselectProjectreference Alt+Enter
sItems.Properties
Debug
COMMANDS KEYBOARD SHORTCUTS
Debug.ApplyCodeChanges Alt+F10
Debug.Autos Ctrl+Alt+V, A
Debug.BreakAll Ctrl+Alt+Break
Debug.BreakatFunction Ctrl+B
Debug.Breakpoints Ctrl+Alt+B
Debug.CallStack Ctrl+Alt+C
Debug.DeleteAllBreakpoints Ctrl+Shift+F9
Debug.DiagnosticsHub.Launch Alt+F2
Debug.Disassembly Ctrl+Alt+D
Debug.DOMExplorer Ctrl+Alt+V, D
Debug.EnableBreakpoint Ctrl+F9
Debug.Exceptions Ctrl+Alt+E
Debug.GoToPreviousCallorIntelliTraceEvent Ctrl+Shift+F11
Debug.Graphics.StartDiagnostics Alt+F5
Debug.Immediate Ctrl+Alt+I
Debug.IntelliTraceCalls Ctrl+Alt+Y, T
Debug.IntelliTraceEvents Ctrl+Alt+Y, F
Debug.JavaScriptConsole Ctrl+Alt+V, C
Debug.Locals Ctrl+Alt+V, L
Debug.LocationToolbar.ProcessCombo Ctrl+5
Debug.LocationToolbar.StackFrameCombo Ctrl+7
Debug.LocationToolbar.ThreadCombo Ctrl+6
COMMANDS KEYBOARD SHORTCUTS
Debug.LocationToolbar.ToggleCurrentThreadFlaggedState Ctrl+8
Debug.LocationToolbar.ToggleFlaggedThreads Ctrl+9
Debug.Memory1 Ctrl+Alt+M, 1
Debug.Memory2 Ctrl+Alt+M, 2
Debug.Memory3 Ctrl+Alt+M, 3
Debug.Memory4 Ctrl+Alt+M, 4
Debug.Modules Ctrl+Alt+U
Debug.ParallelStacks Ctrl+Shift+D, S
Debug.ParallelWatch1 Ctrl+Shift+D, 1
Debug.ParallelWatch2 Ctrl+Shift+D, 2
Debug.ParallelWatch3 Ctrl+Shift+D, 3
Debug.ParallelWatch4 Ctrl+Shift+D, 4
Debug.Processes Ctrl+Alt+Z
Debug.QuickWatch Shift+F9
or
Ctrl+Alt+Q
Debug.RefreshWindowsapp Ctrl+Shift+R
Debug.Registers Ctrl+Alt+G
Debug.Restart Ctrl+Shift+F5
Debug.RunToCursor Ctrl+F10
Debug.SetNextStatement Ctrl+Shift+F10
Debug.ShowCallStackonCodeMap Ctrl+Shift+`
Debug.ShowNextStatement Alt+Num *
Debug.Start F5
Debug.StartWindowsPhoneApplicationAnalysis Alt+F1
Debug.StartWithoutDebugging Ctrl+F5
COMMANDS KEYBOARD SHORTCUTS
Debug.StepInto F11
Debug.StepIntoCurrentProcess Ctrl+Alt+F11
Debug.StepIntoSpecific Shift+Alt+F11
Debug.StepOut Shift+F11
Debug.StepOutCurrentProcess Ctrl+Shift+Alt+F11
Debug.StepOver F10
Debug.StepOverCurrentProcess Ctrl+Alt+F10
Debug.StopDebugging Shift+F5
Debug.StopPerformanceAnalysis Shift+Alt+F2
Debug.Tasks Ctrl+Shift+D, K
Debug.Threads Ctrl+Alt+H
Debug.ToggleBreakpoint F9
Debug.ToggleDisassembly Ctrl+F11
Debug.Watch1 Ctrl+Alt+W, 1
Debug.Watch2 Ctrl+Alt+W, 2
Debug.Watch3 Ctrl+Alt+W, 3
Debug.Watch4 Ctrl+Alt+W, 4
DebuggerContextMenus.BreakpointsWindow.Delete Alt+F9, D
DebuggerContextMenus.BreakpointsWindow.GoToDisassemb Alt+F9, A
ly
DebuggerContextMenus.BreakpointsWindow.GoToSourceCod Alt+F9, S
e
Diagnostics Hub
COMMAND KEYBOARD SHORTCUT
DiagnosticsHub.StopCollection Ctrl+Alt+F2
Edit
COMMANDS
Edit.Copy Ctrl+C
or
Ctrl+Ins
Edit.Cut Ctrl+X
or
Shift+Delete
Edit.CycleClipboardRing Ctrl+Shift+V
or
Ctrl+Shift+Ins
Edit.Delete Delete
Edit.Find Ctrl+F
Edit.FindAllReferences Shift+F12
Edit.FindinFiles Ctrl+Shift+F
Edit.FindNext F3
Edit.FindNextSelected Ctrl+F3
Edit.FindPrevious Shift+F3
Edit.FindPreviousSelected Ctrl+Shift+F3
Edit.GoTo Ctrl+G
Edit.GoToDeclaration Ctrl+F12
Edit.GoToDefinition F12
Edit.GoToFindCombo Ctrl+D
Edit.GoToNextLocation F8
Edit.GoToPrevLocation Shift+F8
Edit.MoveControlUpGrid Up Arrow
Edit.NavigateTo Ctrl+,
Edit.OpenFile Ctrl+Shift+G
Edit.Paste Ctrl+V
or
Shift+Ins
Edit.QuickFindSymbol Shift+Alt+F12
Edit.Redo Ctrl+Y
or
Ctrl+Shift+Z
or
Shift+Alt+Backspace
Edit.RefreshRemoteReferences Ctrl+Shift+J
Edit.Replace Ctrl+H
Edit.ReplaceinFiles Ctrl+Shift+H
Edit.SelectAll Ctrl+A
COMMANDS
Edit.SelectNextControl Tab
Edit.SelectPreviousControl Shift+Tab
Edit.ShowTileGrid Enter
Edit.StopSearch Alt+F3, S
Edit.Undo Ctrl+Z
or
Alt+Backspace
EditorContextMenus.CodeWindow.Breakpoint.BreakpointEditl Alt+F9, L
abels
EditorContextMenus.CodeWindow.CodeMap.ShowItem Ctrl+`
EditorContextMenus.CodeWindow.Execute Ctrl+Alt+F5
or
Ctrl+K, T
File
COMMANDS KEYBOARD SHORTCUTS
File.Exit Alt+F4
File.NewFile Ctrl+N
File.NewProject Ctrl+Shift+N
File.NewWebSite Shift+Alt+N
File.OpenFile Ctrl+O
File.OpenProject Ctrl+Shift+O
File.OpenWebSite Shift+Alt+O
File.Print Ctrl+P
File.SaveAll Ctrl+Shift+S
File.SaveSelectedItems Ctrl+S
File.ViewinBrowser Ctrl+Shift+W
Help
COMMANDS KEYBOARD SHORTCUTS
Help.AddandRemoveHelpContent Ctrl+Alt+F1
Help.F1Help F1
Help.ViewHelp Ctrl+F1
Help.WindowHelp Shift+F1
Load Test
COMMAND KEYBOARD SHORTCUT
LoadTest.JumpToCounterPane Ctrl+R, Q
OtherContextMenus.MicrosoftDataEntityDesignContext.Add Insert
NewDiagram
Project
COMMANDS KEYBOARD SHORTCUTS
Project.AddExistingItem Shift+Alt+A
Project.AddNewItem Ctrl+Shift+A
Project.ClassWizard Ctrl+Shift+X
Project.Override Ctrl+Alt+Ins
Refactor
COMMANDS KEYBOARD SHORTCUTS
Solution Explorer
COMMANDS KEYBOARD SHORTCUTS
SolutionExplorer.OpenFilesFilter Ctrl+[, O
or
Ctrl+[, Ctrl+O
COMMANDS KEYBOARD SHORTCUTS
SolutionExplorer.PendingChangesFilter Ctrl+[, P
or
Ctrl+[, Ctrl+P
SolutionExplorer.SyncWithActiveDocument Ctrl+[, S
or
Ctrl+[, Ctrl+S
Team
COMMANDS KEYBOARD SHORTCUTS
or
Ctrl+0, N
or
Ctrl+0, G
or
Ctrl+0, O
Team.TeamExplorerSearch Ctrl+'
or
Ctrl+0, B
or
Ctrl+0, C
COMMANDS KEYBOARD SHORTCUTS
or
Ctrl+0, D
or
Ctrl+0, H
or
Ctrl+0, M
Ctrl+0, P
or
Ctrl+0, R
or
Ctrl+0, S
or
Ctrl+0, A
or
Ctrl+0, W
Test
COMMANDS KEYBOARD SHORTCUTS
Test Explorer
COMMANDS KEYBOARD SHORTCUTS
TestExplorer.RepeatLastRun Ctrl+R, L
TestExplorer.RunAllTests Ctrl+R, A
TestExplorer.RunAllTestsInContext Ctrl+R, T
Tools
COMMANDS KEYBOARD SHORTCUTS
Tools.AttachtoProcess Ctrl+Alt+P
Tools.GoToCommandLine Ctrl+/
View
COMMANDS KEYBOARD SHORTCUTS
View.AllWindows Shift+Alt+M
View.BrowseNext Ctrl+Shift+1
View.BrowsePrevious Ctrl+Shift+2
View.CallHierarchy Ctrl+Alt+K
View.ClassView Ctrl+Shift+C
View.CodeDefinitionWindow Ctrl+\, D
or
Ctrl+\, Ctrl+D
View.CommandWindow Ctrl+Alt+A
COMMANDS KEYBOARD SHORTCUTS
View.DataSources Shift+Alt+D
View.DocumentOutline Ctrl+Alt+T
View.EditLabel F2
View.ErrorList Ctrl+\, E
or
Ctrl+\, Ctrl+E
View.F#Interactive Ctrl+Alt+F
View.FindSymbolResults Ctrl+Alt+F12
View.ForwardBrowseContext Ctrl+Shift+7
View.FullScreen Shift+Alt+Enter
View.NavigateBackward Ctrl+-
View.NavigateForward Ctrl+Shift+-
View.NextError Ctrl+Shift+F12
View.Notifications Ctrl+W, N
or
Ctrl+W, Ctrl+N
View.ObjectBrowser Ctrl+Alt+J
View.Output Ctrl+Alt+O
View.PopBrowseContex Ctrl+Shift+8
View.PropertiesWindow F4
View.PropertyPages Shift+F4
View.ResourceView Ctrl+Shift+E
View.ServerExplorer Ctrl+Alt+S
COMMANDS KEYBOARD SHORTCUTS
View.ShowSmartTag Shift+Alt+F10
or
Ctrl+.
View.SolutionExplorer Ctrl+Alt+L
View.TaskList Ctrl+\, T
or
Ctrl+\, Ctrl+T
View.Toolbox Ctrl+Alt+X
View.ViewCode F7
View.ViewDesigner Shift+F7
View.WebBrowser Ctrl+Alt+R
View.ZoomIn Ctrl+Shift+.
View.ZoomOut Ctrl+Shift+,
Window
COMMANDS KEYBOARD SHORTCUTS
Window.ActivateDocumentWindow Esc
Window.AddTabtoSelection Ctrl+Shift+Alt+Space
Window.CloseDocumentWindow Ctrl+F4
Window.CloseToolWindow Shift+Esc
Window.KeepTabOpen Ctrl+Alt+Home
Window.MovetoNavigationBar Ctrl+F2
Window.NextDocumentWindow Ctrl+F6
Window.NextDocumentWindowNav Ctrl+Tab
COMMANDS KEYBOARD SHORTCUTS
Window.NextPane Alt+F6
Window.NextSplitPane F6
Window.NextTab Ctrl+Alt+PgDn
or
Ctrl+PgDn
Window.NextTabandAddtoSelection Ctrl+Shift+Alt+PgDn
Window.NextToolWindowNav Alt+F7
Window.PreviousDocumentWindow Ctrl+Shift+F6
Window.PreviousDocumentWindowNav Ctrl+Shift+Tab
Window.PreviousPane Shift+Alt+F6
Window.PreviousSplitPane Shift+F6
Window.PreviousTab Ctrl+Alt+PgUp
or
Ctrl+PgUp
Window.PreviousTabandAddtoSelection Ctrl+Shift+Alt+PgUp
Window.PreviousToolWindowNav Shift+Alt+F7
Window.QuickLaunch Ctrl+Q
Window.QuickLaunchPreviousCategory Ctrl+Shift+Q
Window.ShowDockMenu Alt+-
Window.SolutionExplorerSearch Ctrl+;
Window.WindowSearch Alt+`
Azure
COMMANDS KEYBOARD SHORTCUTS
OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+PgDn
eProperties.Down5
OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+End
eProperties.ToBottom
OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+Home
eProperties.ToTop
OtherContextMenus.MicrosoftDataEntityDesignContext.Mov Alt+PgUp
eProperties.Up5
OtherContextMenus.MicrosoftDataEntityDesignContext.Refac Ctrl+R, R
tor.Rename
OtherContextMenus.MicrosoftDataEntityDesignContext.Rem Shift+Del
ovefromDiagram
View.EntityDataModelBrowser Ctrl+1
View.EntityDataModelMappingDetails Ctrl+2
Class Diagram
COMMANDS KEYBOARD SHORTCUTS
ClassDiagram.Collapse Num -
ClassDiagram.Expand Num +
Edit.Delete Ctrl+Del
Edit.ExpandCollapseBaseTypeList Shift+Alt+B
Edit.NavigateToLollipop Shift+Alt+L
Edit.RemovefromDiagram Delete
View.ViewCode Enter
OtherContextMenus.UITestEditorContextMenu.CopyReferenc Ctrl+C
etoClipboard
OtherContextMenus.UITestEditorContextMenu.InsertDelayBe Ctrl+Alt+D
fore
OtherContextMenus.UITestEditorContextMenu.LocateAll Shift+Alt+L
OtherContextMenus.UITestEditorContextMenu.LocatetheUIC Ctrl+Shift+L
ontrol
OtherContextMenus.UITestEditorContextMenu.Movecode Ctrl+Alt+C
OtherContextMenus.UITestEditorContextMenu.Splitintoanew Ctrl+Shift+T
method
DataSet Editor
COMMANDS KEYBOARD SHORTCUTS
OtherContextMenus.ColumnContext.InsertColumn Insert
OtherContextMenus.DbTableContext.Add.Column Ctrl+L
Difference Viewer
Diff.NextDifference F8
Diff.PreviousDifference Shift+F8
EditorContextMenus.CodeWindow.AddComment Ctrl+Shift+K
EditorContextMenus.CodeWindow.EditLocalFile Ctrl+Shift+P
DOM Explorer
COMMANDS KEYBOARD SHORTCUTS
DOMExplorer.Refresh F5
DOMExplorer.SelectElement Ctrl+B
DOMExplorer.ShowLayout Ctrl+Shift+I
F# Interactive
COMMAND KEYBOARD SHORTCUT
OtherContextMenus.FSIConsoleContext.CancelInteractiveEval Ctrl+Break
uation
ArchitectureContextMenus.DirectedGraphContextMenu.Adva Insert
nced.Add.AddNode
ArchitectureContextMenus.DirectedGraphContextMenu.Adva B
nced.Select.BothDependencies
ArchitectureContextMenus.DirectedGraphContextMenu.Adva I
nced.Select.IncomingDependencies
ArchitectureContextMenus.DirectedGraphContextMenu.Adva O
nced.Select.OutgoingDependencies
ArchitectureContextMenus.DirectedGraphContextMenu.New Ctrl+Shift+K
Comment
or
Ctrl+E, C
ArchitectureContextMenus.DirectedGraphContextMenu.Remo Delete
ve
ArchitectureContextMenus.DirectedGraphContextMenu.Rena F2
me
Graphics Diagnostics
COMMANDS KEYBOARD SHORTCUTS
Debug.Graphics.CaptureFrame None
Graphics.ZoomToActualSize Shift+Alt+0
Graphics.ZoomToFitInWindow Shift+Alt+9
Graphics.ZoomIn Shift+Alt+=
Graphics.ZoomOut Shift+Alt+-
HTML Editor
COMMAND KEYBOARD SHORTCUT
Format.Bold Ctrl+B
Format.ConverttoHyperlink Ctrl+L
Format.InsertBookmark Ctrl+Shift+L
Format.Italic Ctrl+I
Format.Underline Ctrl+U
View.ASP.NETNonvisualControls Ctrl+Shift+N
View.NextView Ctrl+PgDn
View.ShowSmartTag Shift+Alt+F10
View.ViewMarkup Shift+F7
Window.PreviousTab Ctrl+PgUp
View.NextView Ctrl+PgDn
View.SynchronizeViews Ctrl+Shift+Y
View.ViewDesigner Shift+F7
Window.PreviousTab Ctrl+PgUp
Layer Diagram
COMMAND KEYBOARD SHORTCUT
Edit.Delete Shift+Delete
Edit.EditCell F2
Edit.Remove Delete
Edit.RemoveRow Ctrl+Delete
Edit.SelectionCancel Escape
Resources.Audio Ctrl+4
COMMANDS KEYBOARD SHORTCUTS
Resources.Files Ctrl+5
Resources.Icons Ctrl+3
Resources.Images Ctrl+2
Resources.Other Ctrl+6
Resources.Strings Ctrl+1
TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+1
onLeftWindow
TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+2
onResultWindow
TeamFoundationContextMenus.MergeContextMenu.SetFocus Alt+3
onRightWindow
SQL.SSDTSchemaCompareCompare Shift+Alt+C
SQL.SSDTSchemaCompareGenerateScript Shift+Alt+G
SQL.SSDTSchemaCompareNextChange Shift+Alt+.
SQL.SSDTSchemaComparePreviousChange Shift+Alt+,
SQL.SSDTSchemaCompareStop Alt+Break
SQL.SSDTSchemaCompareWriteUpdates Shift+Alt+U
CommitAllEdits Shift+Alt+U
COMMANDS KEYBOARD SHORTCUTS
SQL.ExpandWildcards Ctrl+R, E
or
Ctrl+R, Ctrl+E
SQL.FullyqualifyNames Ctrl+R, Q
or
Ctrl+R, Ctrl+Q
SQL.MovetoSchema Ctrl+R, M
or
Ctrl+R, Ctrl+M
SQL.Rename F2
or
Ctrl+R, R
or
Ctrl+R, Ctrl+R
ViewFileInScriptPanel Shift+Alt+PgDn
CommitAllEdits Shift+Alt+U
SQL.ExecuteWithDebugger Alt+F5
SQL.ExpandWildcards Ctrl+R, E
or
Ctrl+R, Ctrl+E
SQL.FullyqualifyNames Ctrl+R, Q
or
Ctrl+R, Ctrl+Q
SQL.MovetoSchema Ctrl+R, M
or
Ctrl+R, Ctrl+M
COMMANDS KEYBOARD SHORTCUTS
SQL.Rename F2
or
Ctrl+R, R
or
Ctrl+R, Ctrl+R
SQL.TSqlEditorCancelQuery Alt+Break
SQL.TSqlEditorExecuteQuery Ctrl+Shift+E
SQL.TSqlEditorResultsAsFile Ctrl+D, F
SQL.TSqlEditorResultsAsGrid Ctrl+D, G
SQL.TSqlEditorResultsAsText Ctrl+D, T
SQL.TSqlEditorShowEstimatedPlan Ctrl+D, E
SQL.TSqlEditorToggleExecutionPlan Ctrl+D, A
SQL.TSqlEditorToggleResultsPane Ctrl+D, R
TSqlEditorCloneQuery Ctrl+Alt+N
TSqlEditorDatabaseCombo Shift+Alt+PgDn
SQL.TSqlEditorCancelQuery Alt+Break
SQL.TSqlEditorExecuteQuery Ctrl+Shift+E
SQL.TSqlEditorResultsAsFile Ctrl+D, F
SQL.TSqlEditorResultsAsGrid Ctrl+D, G
SQL.TSqlEditorResultsAsText Ctrl+D, T
SQL.TSqlEditorShowEstimatedPlan Ctrl+D, E
SQL.TSqlEditorToggleExecutionPlan Ctrl+D, A
SQL.TSqlEditorToggleResultsPane Ctrl+D, R
TSqlEditorCloneQuery Ctrl+Alt+N
COMMANDS KEYBOARD SHORTCUTS
TSqlEditorDatabaseCombo Shift+Alt+PgDn
Page Inspector
COMMAND KEYBOARD SHORTCUT
PageInspector.Minimize F12
Query Designer
COMMANDS KEYBOARD SHORTCUTS
QueryDesigner.CancelRetrievingData Ctrl+T
QueryDesigner.Criteria Ctrl+2
QueryDesigner.Diagram Ctrl+1
QueryDesigner.ExecuteSQL Ctrl+R
QueryDesigner.GotoRow Ctrl+G
QueryDesigner.JoinMode Ctrl+Shift+J
QueryDesigner.Results Ctrl+4
QueryDesigner.SQL Ctrl+3
Query Results
COMMANDS KEYBOARD SHORTCUTS
SQL.QueryResultsNewRow Alt+End
SQL.QueryResultsRefresh Shift+Alt+R
SQL.QueryResultsStop Alt+Break
Report Designer
COMMANDS KEYBOARD SHORTCUTS
Edit.BreakLine Enter
Edit.InsertTab Tab
Edit.LineUp Up Arrow
Edit.SelectionCancel Esc
Edit.TabLeft Shift+Tab
View.ReportData Ctrl+Alt+D
Sequence Diagram
COMMANDS KEYBOARD SHORTCUTS
ArchitectureDesigner.Sequence.NavigateToCode F12
Edit.Delete Shift+Del
Settings Designer
COMMANDS KEYBOARD SHORTCUTS
Edit.EditCell F2
COMMANDS KEYBOARD SHORTCUTS
Edit.RemoveRow Ctrl+Delete
Edit.SelectionCancel Esc
View.ViewCode F7
Solution Explorer
COMMAND KEYBOARD SHORTCUT
Team Explorer
COMMAND KEYBOARD SHORTCUT
Edit.Delete Delete
File.Rename F2
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+Home
erNavigation
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+0
erPageContent
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+1
erSection1Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+2
erSection2Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+3
erSection3Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+4
erSection4Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+5
erSection5Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+6
erSection6Content
COMMAND KEYBOARD SHORTCUT
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+7
erSection7Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+8
erSection8Content
TeamFoundationContextMenus.Commands.GoToTeamExplor Alt+9
erSection9Content
TeamFoundationContextMenus.MyWorkPageInProgress.TfsC Shift+Alt+C
ontextMyWorkPageCreateCopyWI
TeamFoundationContextMenus.MyWorkPageInProgress.TfsC Shift+Alt+L
ontextMyWorkPageNewLinkedWI
View.Refresh F5
View.Refresh F5
Test Explorer
COMMAND KEYBOARD SHORTCUT
TestExplorer.OpenTest F12
Text Editor
COMMANDS KEYBOARD SHORTCUTS
Edit.BreakLine Enter
or
Shift+Enter
Edit.CharTranspose Ctrl+T
Edit.CompleteWord Ctrl+Space
or
Alt+Right Arrow
Edit.CopyParameterTip Ctrl+Shift+Alt+C
Edit.DecreaseFilterLevel Alt+,
Edit.DeleteBackwards Backspace
or
Shift+Bkspce
Edit.DocumentEnd Ctrl+End
Edit.DocumentEndExtend Ctrl+Shift+End
Edit.DocumentStart Ctrl+Home
Edit.DocumentStartExtend Ctrl+Shift+Home
Edit.GotoBrace Ctrl+]
Edit.GotoBraceExtend Ctrl+Shift+]
Edit.IncreaseFilterLevel Alt+.
Edit.IncrementalSearch Ctrl+I
Edit.InsertTab Tab
Edit.LineCut Ctrl+L
Edit.LineDelete Ctrl+Shift+L
Edit.LineEnd End
Edit.LineEndExtend Shift+End
Edit.LineEndExtendColumn Shift+Alt+End
Edit.LineOpenAbove Ctrl+Enter
Edit.LineOpenBelow Ctrl+Shift+Enter
Edit.LineStart Home
Edit.LineStartExtend Shift+Home
Edit.LineStartExtendColumn Shift+Alt+Home
Edit.LineTranspose Shift+Alt+T
Edit.LineUp Up Arrow
Edit.ListMembers Ctrl+J
COMMANDS KEYBOARD SHORTCUTS
Edit.MakeLowercase Ctrl+U
Edit.MakeUppercase Ctrl+Shift+U
Edit.OvertypeMode Insert
Edit.PageDown PgDn
Edit.PageDownExtend Shift+PgDn
Edit.PageUp PgUp
Edit.PageUpExtend Shift+PgUp
Edit.ParameterInfo Ctrl+Shift+Spacebar
Edit.PasteParameterTip Ctrl+Shift+Alt+P
Edit.PeekBackward Ctrl+Alt+-
Edit.PeekDefinition Alt+F12
Edit.PeekForward Ctrl+Alt+=
Edit.ReverseIncrementalSearch Ctrl+Shift+I
Edit.SelectCurrentWord Ctrl+W
Edit.SelectionCancel Escape
Edit.SelectToLastGoBack Ctrl+=
Edit.ShowCodeLensMenu Alt+`
Edit.TabLeft Shift+Tab
Edit.ToggleCompletionMode Ctrl+Alt+Space
Edit.ViewBottom Ctrl+PgDn
Edit.ViewBottomExtend Ctrl+Shift+PgDn
Edit.ViewTop Ctrl+PgUp
Edit.ViewTopExtend Ctrl+Shift+PgUp
Edit.WordDeleteToEnd Ctrl+Delete
Edit.WordDeleteToStart Ctrl+Backspace
Edit.WordTranspose Ctrl+Shift+T
EditorContextMenus.CodeWindow.ExecuteInInteractive Alt+Enter
COMMANDS KEYBOARD SHORTCUTS
EditorContextMenus.CodeWindow.ExecuteLineInInteractive Alt+'
TeamFoundationContextMenus.Annotate.TfsAnnotateMoveN Alt+PgDn
extRegion
TeamFoundationContextMenus.Annotate.TfsAnnotateMovePr Alt+PgUp
eviousRegion
Edit.Delete Shift+Del
Edit.DeleteFromModel Shift+Del
Edit.DeleteFromModel Shift+Del
Edit.DeleteFromModel Shift+Del
VC Accelerator Editor
COMMANDS KEYBOARD SHORCTUTS
Edit.NewAccelerator Insert
Edit.NextKeyTyped Ctrl+W
VC Dialog Editor
COMMANDS KEYBOARD SHORCTUTS
Edit.MoveControlUp Up Arrow
Format.AlignCenters Shift+F9
Format.AlignMiddles F9
Format.ButtonBottom Ctrl+B
Format.ButtonRight Ctrl+R
Format.CenterHorizontal Ctrl+Shift+F9
Format.CenterVertical Ctrl+F9
Format.CheckMnemonics Ctrl+M
Format.SizetoContent Shift+F7
or
Alt+Left Arrow
COMMANDS KEYBOARD SHORCTUTS
or
Alt+Down Arrow
Format.TabOrder Ctrl+D
Format.TestDialog Ctrl+T
Format.ToggleGuides Ctrl+G
VC Image Editor
COMMANDS KEYBOARD SHORTCUTS
Image.AirbrushTool Ctrl+A
Image.BrushTool Ctrl+B
Image.CopyandOutlineSelection Ctrl+Shift+U
Image.DrawOpaque Ctrl+J
Image.EllipseTool Alt+P
Image.EraseTool Ctrl+Shift+I
Image.FilledEllipseTool Ctrl+Shift+Alt+P
Image.FilledRectangleTool Ctrl+Shift+Alt+R
Image.FilledRoundedRectangleTool Ctrl+Shift+Alt+W
Image.FillTool Ctrl+F
Image.FlipHorizontal Ctrl+H
Image.FlipVertical Shift+Alt+H
Image.LargerBrush Ctrl+=
Image.LineTool Ctrl+L
Image.MagnificationTool Ctrl+M
Image.Magnify Ctrl+Shift+M
Image.NewImageType Insert
COMMANDS KEYBOARD SHORTCUTS
Image.NextColor Ctrl+]
or
Ctrl+Right Arrow
Image.NextRightColor Ctrl+Shift+]
or
Ctrl+Shift+Right Arrow
Image.OutlinedEllipseTool Shift+Alt+P
Image.OutlinedRectangleTool Shift+Alt+R
Image.OutlinedRoundedRectangleTool Shift+Alt+W
Image.PencilTool Ctrl+I
Image.PreviousColor Ctrl+[
or
Ctrl+Left Arrow
Image.PreviousRightColor Ctrl+Shift+[
or
Ctrl+Shift+Left Arrow
Image.RectangleSelectionTool Shift+Alt+S
Image.RectangleTool Alt+R
Image.Rotate90Degrees Ctrl+Shift+H
Image.RoundedRectangleTool Alt+W
Image.ShowGrid Ctrl+Alt+S
Image.ShowTileGrid Ctrl+Shift+Alt+S
Image.SmallBrush Ctrl+.
Image.SmallerBrush Ctrl+-
Image.TextTool Ctrl+T
Image.UseSelectionasBrush Ctrl+U
COMMANDS KEYBOARD SHORTCUTS
Image.ZoomIn Ctrl+Shift+.
or
Ctrl+Up Arrow
Image.ZoomOut Ctrl+Shift+,
or
Ctrl+Down Arrow
VC String Editor
COMMAND KEYBOARD SHORTCUT
Edit.NewString Insert
View Designer
COMMANDS KEYBOARD SHORTCUTS
QueryDesigner.CancelRetrievingData Ctrl+T
QueryDesigner.Criteria Ctrl+2
QueryDesigner.Diagram Ctrl+1
QueryDesigner.ExecuteSQL Ctrl+R
QueryDesigner.GotoRow Ctrl+G
QueryDesigner.JoinMode Ctrl+Shift+J
QueryDesigner.Results Ctrl+4
QueryDesigner.SQL Ctrl+3
Visual Studio
COMMAND KEYBOARD SHORTCUT
OtherContextMenus.ORDesignerContext.HideMethodsPane Ctrl+1
Edit.BreakLine Enter
COMMANDS KEYBOARD SHORTCUTS
Edit.DocumentEnd End
Edit.DocumentEndExtend Shift+End
Edit.DocumentStart Home
Edit.DocumentStartExtend Shift+Home
Edit.InsertTab Tab
Edit.LineUp Up Arrow
Edit.SelectionCancel Escape
Edit.TabLeft Shift+Tab
Edit.CreateCopyofWorkItem Shift+Alt+C
Edit.RefreshWorkItem F5
Team.NewLinkedWorkItem Shift+Alt+L
Edit.CreateCopyofWorkItem Shift+Alt+C
Team.NewLinkedWorkItem Shift+Alt+L
Team.Refresh F5
Window.Toggle Shift+Alt+V
Edit.CreateCopyofWorkItem Shift+Alt+C
Team.GotoNextWorkItem Shift+Alt+N
Team.GotoPreviousWorkItem Shift+Alt+P
Team.NewLinkedWorkItem Shift+Alt+L
Team.Refresh F5
Window.Toggle Shift+Alt+V
Workflow Designer
COMMANDS KEYBOARD SHORTCUTS
COMMANDS KEYBOARD SHORTCUTS
Edit.CompleteWord Ctrl+K, W
or
Ctrl+K, Ctrl+W
or
Ctrl+Spacebar
or
Alt+Right Arrow
Edit.DecreaseFilterLevel Alt+,
Edit.IncreaseFilterLevel Alt+.
Edit.ListMembers Ctrl+K, L
or
Ctrl+K, Ctrl+L
or
Ctrl+J
Edit.ParameterInfo Ctrl+K, P
or
Ctrl+K, Ctrl+P
or
Ctrl+Shift+Spacebar
Edit.QuickInfo Ctrl+K, I
or
Ctrl+K, Ctrl+I
or
Ctrl+E, C
WorkflowDesigner.CollapseAll or
or
Ctrl+E, F
COMMANDS KEYBOARD SHORTCUTS
or
Ctrl+E, N
or
Ctrl+E, X
or
Ctrl+E, E
or
Ctrl+E, P
or
Ctrl+E, M
WorkflowDesigner.NavigateThroughDesigner Ctrl+Alt+F6
or
Ctrl+E, R
or
Ctrl+E, A
or
Ctrl+E, I
or
Ctrl+E, O
COMMANDS KEYBOARD SHORTCUTS
or
Ctrl+E, V
or
Ctrl+E, S
WorkflowDesigner.ZoomIn Ctrl+Num +
WorkflowDesigner.ZoomOut Ctrl+Num -
XAML UI Designer
COMMANDS KEYBOARD SHORTCUTS
Design.FitAll Ctrl+0
Design.ShowHandles F9
Design.ZoomIn Ctrl+Alt+=
Design.ZoomOut Ctrl+Alt+-
Format.EditText F2
Format.ResetLayout.All Ctrl+Shift+R
View.EdgeLeftMoveLeft Ctrl+Shift+,
View.EdgeLeftMoveRight Ctrl+Shift+.
View.EdgeRightMoveLeft Ctrl+Shift+Alt+,
View.EdgeRightMoveRight Ctrl+Shift+Alt+.
View.ShowPropertyMarkerMenu Ctrl+Spacebar
XML (Text) Editor
COMMANDS KEYBOARD SHORTCUTS
XML.StartXSLTDebugging Alt+F5
XML.StartXSLTWithoutDebugging Ctrl+Alt+F5
OtherContextMenus.GraphView.RemovefromWorkspace Delete
XsdDesigner.ShowContentModelView Ctrl+2
XsdDesigner.ShowGraphView Ctrl+3
XsdDesigner.ShowStartView Ctrl+1
See Also
Image Editor for Icons
Using IntelliSense
Using IntelliSense
10/18/2017 • 4 min to read • Edit Online
IntelliSense is the general term for a number of features: List Members, Parameter Info, Quick Info, and Complete
Word. These features help you to learn more about the code you are using, keep track of the parameters you are
typing, and add calls to properties and methods with only a few keystrokes.
Many aspects of IntelliSense are language-specific. For more information about IntelliSense for different
languages, see the topics listed under See Also.
List Members
A list of valid members from a type (or namespace) appears after you type a trigger character (for example, a
period ( . ) in managed code or :: in C++). If you continue typing characters, the list is filtered to include only
the members that begin with those characters or where the beginning of any word within the name starts with
those characters. IntelliSense also performs "camel case" matching, so you can just type the first letter of each
camel-cased word in the member name to see the matches.
After selecting an item, you can insert it into your code by pressing TAB or by typing a space. If you select an item
and type a period, the item appears followed by the period, which brings up another member list. When you
select an item but before you insert it, you get Quick Info for the item.
In the member list, the icon to the left represents the type of the member, such as namespace, class, function, or
variable. For a list of icons, see Class View and Object Browser Icons. The list may be quite long, so you can press
PAGE UP and PAGE DOWN to move up or down in the list.
You can invoke the List Members feature manually by typing CTRL+J, clicking Edit/IntelliSense/List Members,
or clicking the List Members button on the editor toolbar. When it is invoked on a blank line or outside a
recognizable scope, the list displays symbols in the global namespace.
To turn List Members off by default (so that it does not appear unless specifically invoked), go to
Tools/Options/All Languages and deselect Auto list members. If you want to turn off List Members only for a
specific language, go to the General settings for that language.
You can also change to suggestion mode, in which only the text you type is inserted into the code. For example, if
you enter an identifier that is not in the list and press TAB, in completion mode the entry would replace the typed
identifier. To toggle between completion mode and suggestion mode, press CTRL+ALT+SPACEBAR or click
Edit/IntelliSense/Toggle Completion Mode.
Parameter Info
Parameter Info gives you information about the number, names, and types of parameters required by a method,
attribute generic type parameter (in C#), or template (in C++).
The parameter in bold indicates the next parameter that is required as you type the function. For overloaded
functions, you can use the UP and DOWN arrow keys to view alternative parameter information for the function
overloads.
When you annotate functions and parameters with XML Documentation comments, the comments will display as
Parameter Info. For more information, see Supplying XML Code Comments.
You can manually invoke Parameter Info by clicking Edit IntelliSense/Parameter Info, typing
CTRL+SHIFT+SPACE, or clicking the Parameter Info button on the editor toolbar.
Quick Info
Quick Info displays the complete declaration for any identifier in your code.
When you select a member from the List Members box, Quick Info also appears.
You can manually invoke Quick Info by clicking Edit/IntelliSense/Quick Info, typing CTRL+I, or clicking the
Quick Info button on the editor toolbar.
If a function is overloaded, IntelliSense may not display information for all forms of the overload.
You can turn Quick Info off In C++ by setting Tools/Options/Text Editor/C/C++/Advanced/Auto Quick Info
to false .
Complete Word
Complete Word completes the rest of a variable, command, or function name once you have entered enough
characters to disambiguate the term. You can invoke Complete Word by clicking Edit/IntelliSense/Complete
Word, typing CTRL+SPACE, or clicking the Complete Word button on the editor toolbar.
IntelliSense Options
IntelliSense options are on by default. To turn them off, click Tools/Options/Text Editor and deselect
Parameter information or Auto list members if you do not want the List Members feature.
Troubleshooting IntelliSense
The IntelliSense options may not work as you expect in certain cases.
The cursor is below a code error. You might not be able to use IntelliSense if an incomplete function or other
error exists in the code above the cursor because IntelliSense might not be able to parse the code elements. You
can resolve this problem by commenting out the applicable code.
The cursor is in a code comment. You can't use IntelliSense if the cursor is in a comment in your source file.
The cursor is in a string literal. You can't use IntelliSense if the cursor is in the quotation marks around a string
literal, as in the following example:
The automatic options are turned off. By default, IntelliSense works automatically, but you can disable it. Even
if automatic statement completion is disabled, you can invoke an IntelliSense feature.
See Also
Visual Basic-Specific IntelliSense
Visual C# IntelliSense
JavaScript IntelliSense
Supplying XML Code Comments
Visual Basic-Specific IntelliSense
10/18/2017 • 1 min to read • Edit Online
The Visual Basic source code editor offers the following IntelliSense features:
Syntax tips
Syntax tips display the syntax of the statement that you are typing. This is useful for statements such as
Declare.
Automatic Completion
Completion on various keywords
For example, if you type goto and a space, IntelliSense will display a list of the defined labels in a drop-
down menu. Other supported keywords include Exit , Implements , Option , and Declare .
Completion on Enum and Boolean
When a statement will refer to a member of an enumeration, IntelliSense will display a list of the members
of the Enum . When a statement will refer to a Boolean , IntelliSense will display a true-false drop-down
menu.
Completion can be turned off by default by deselecting Auto list members from the General property
page in the Visual Basic folder.
You can manually invoke completion by invoking List Members, Complete Word, or ALT+RIGHT ARROW.
For more information, see Using IntelliSense.
IntelliSense in Zone
IntelliSense in Zone assists Visual Basic developers who need to deploy applications through ClickOnce and are
constrained to partial trust settings. This feature:
Enables you to choose the permissions the application will run with.
Display APIs in the chosen Zone as available in List Members, and display APIs that require additional
permissions as unavailable.
For more information, see Code Access Security for ClickOnce Applications.
See Also
Using IntelliSense
Filtered Completion Lists in Visual Basic
10/18/2017 • 1 min to read • Edit Online
In Visual Basic, IntelliSense completion lists have two tab controls located near the bottom of the lists. The
Common tab, which is selected by default, displays items that are most often used to complete the statement that
you are writing. The All tab displays all items that are available for automatic completion, including those that are
also on the Common tab.
See Also
Using IntelliSense
Visual Basic-Specific IntelliSense
Visual C# IntelliSense
10/18/2017 • 8 min to read • Edit Online
Visual C# IntelliSense is available when coding in the editor, and while debugging in the Immediate Mode
command window.
Completion Lists
The IntelliSense completion lists in Visual C# contain tokens from List Members, Complete Word, and more. It
provides quick access to:
Members of a type or namespace
Variables, commands, and functions names
Code snippets
Language Keywords
Extension Methods
The Completion List in C# is also smart enough to filter out irrelevant tokens and pre-select a token based on
context. For more information, see Filtered Completion Lists.
Code Snippets in Completion Lists
In Visual C#, the completion list includes code snippets to help you easily insert predefined bodies of code into
your program. Code snippets appear in the completion list as the snippet's shortcut text. For more information
about code snippets that are available in Visual C# by default, see Visual C# Code Snippets.
Language Keywords in Completion Lists
In Visual C#, the completion list also includes language keywords. For more information about C# language
keywords, see C# Keywords.
Extension Methods in Completion Lists
In Visual C#, the completion list includes Extension Methods that are in scope.
NOTE
The completion list does not display all extension methods for String objects.
Extension methods use a different icon than instance methods. For a listing of list icons, see Class View and Object
Browser Icons. When an instance method and extension method with the same name are both in scope, the
completion list displays the extension method icon.
Filtered Completion Lists
IntelliSense removes unnecessary members from the completion list by using filters. Visual C# filters the
completion lists that appear for these items:
Interfaces and base classes: IntelliSense automatically removes items from the interface and base class
completion lists, in both class declaration base and interface lists and constraint lists. For example, enums do
not appear in the completion list for base classes, because enums cannot be used for base classes. The
completion list of base classes only contains interfaces and namespaces. If you select an item in the list and
then type a comma, IntelliSense removes base classes from the completion list because Visual C# does not
support multiple inheritance. The same behavior occurs for constraint clauses also.
Attributes: When you apply an attribute to a type, the completion list is filtered so that the list only contains
those types that descend from the namespaces that contain those types, such as Attribute.
Catch clauses
Object initializers: Only members that can be initialized will appear in the completion list.
new keyword: When you type new and then press the SPACEBAR, a completion list appears. An item is
automatically selected in the list, based on the context in your code. For example, items are automatically
selected in the completion list for declarations and for return statements in methods.
enum keyword: When you press the SPACEBAR after an equal sign for an enum assignment, a completion
list appears. An item is automatically selected in the list, based on the context in your code. For example,
items are automatically selected in the completion list after you type the keyword return and when you
make a declaration.
as and is operators: A filtered completion list is displayed automatically when you press the SPACEBAR
after you have typed the as or is keyword.
Events: When you type the keyword event , the completion list only contains delegate types.
Parameter help automatically sorts to the first method overload that matches the parameters as you enter
them. If multiple method overloads are available, you can use the up and down arrows to navigate to the
next possible overload in the list.
override
When you type override and then press SPACEBAR, IntelliSense displays all of the valid base class members that
you can override in a pop-up list box. Typing the return type of the method after override will prompt IntelliSense
to only show methods that return the same type. When IntelliSense cannot find any matches, it will display all of
the base class members.
If you press TAB, IntelliSense automatically finishes the statement for you and displays the event handler reference
as selected text in the Code Editor. To complete the automatic event hookup, IntelliSense prompts you to press the
TAB key again to create an empty stub for the event handler.
NOTE
If a new delegate that is created by IntelliSense references an existing event handler, IntelliSense communicates this
information in the tooltip. You can then modify this reference; the text is already selected in the Code Editor. Otherwise,
automatic event hookup is complete at this point.
If you press TAB, IntelliSense stubs out a method with the correct signature and puts the cursor in the body of your
event handler.
NOTE
Use the Navigate Backward command on the View menu (CTRL+-) to go back to the event hookup statement.
See Also
Visual Studio IDE
Walkthrough: test-first development with the
Generate From Usage feature
10/18/2017 • 7 min to read • Edit Online
This topic demonstrates how to use the Generate From Usage feature, which supports test-first development.
Test-first development is an approach to software design in which you first write unit tests based on product
specifications, and then write the source code that is required to make the tests succeed. Visual Studio supports
test-first development by generating new types and members in the source code when you first reference them in
your test cases, before they are defined.
Visual Studio generates the new types and members with minimal interruption to your workflow. You can create
stubs for types, methods, properties, fields, or constructors without leaving your current location in code. When you
open a dialog box to specify options for type generation, the focus returns immediately to the current open file
when the dialog box closes.
The Generate From Usage feature can be used with test frameworks that integrate with Visual Studio. In this topic,
the Microsoft Unit Testing Framework is demonstrated.
NOTE
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following
instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more
information, see Personalizing the IDE.
2. In Solution Explorer, right-click the solution icon at the top, choose Add, and then choose New Project. In
the left pane of the New Project dialog box, choose Test.
3. In the middle pane, choose Unit Test Project and accept the default name of UnitTestProject1. The
following illustration shows the dialog box when it appears in Visual C#. In Visual Basic, the dialog box looks
similar.
4. Choose OK to close the New Project dialog box.
To add a reference to the Class Library project
1. In Solution Explorer, under your unit test project, right-click the References entry and choose Add
Reference.
2. In the Reference Manager dialog box, select Projects and then select the class library project.
3. Choose OK to close the Reference Manager dialog box.
4. Save your solution. You are now ready to begin writing tests.
To generate a new class from a unit test
1. The test project contains a file that is named UnitTest1. Double-click this file in Solution Explorer to open it
in the code editor. A test class and test method have been generated.
2. Locate the declaration for class UnitTest1 and rename it to AutomobileTest .
NOTE
IntelliSense now provides two alternatives for IntelliSense statement completion: completion mode and suggestion
mode. Use suggestion mode for situations in which classes and members are used before they are defined. When an
IntelliSense window is open, you can press Ctrl+Alt+SPACEBAR to toggle between completion mode and
suggestion mode. See Using IntelliSense for more information. Suggestion mode will help when you are typing
Automobile in the next step.
7. Click OK to close the dialog box and create the new file.
8. In Solution Explorer, look under the GFUDemo_VB or GFUDemo_CS project node to verify that the new
Automobile.vb or Automobile.cs file is there. In the code editor, the focus is still in
AutomobileTest.DefaultAutomobileIsInitializedCorrectly , which enables you to continue to write your test
with a minimum of interruption.
To generate a property stub
Assume that the product specification states that the Automobile class has two public properties named Model and
TopSpeed . These properties must be initialized with default values of "Not specified" and -1 by the default
constructor. The following unit test will verify that the default constructor sets the properties to their correct default
values.
1. Add the following line of code to the DefaultAutomobileIsInitializedCorrectly test method.
2. Because the code references two undefined properties on Automobile , a wavy underline appears under
Model and TopSpeed . Hover over Model and choose the Quick Actions light bulb, then choose Generate
property 'Automobile.Model'.
3. Generate a property stub for the TopSpeed property in the same way.
In the Automobile class, the types of the new properties are correctly inferred from the context.
To generate a stub for a new constructor
Now we'll create a test method that will generate a constructor stub to initialize the Model and TopSpeed
properties. Later, you'll add more code to complete the test.
1. Add the following additional test method to your AutomobileTest class.
[TestMethod]
public void AutomobileWithModelNameCanStart()
{
string model = "Contoso";
int topSpeed = 199;
Automobile myAuto = new Automobile(model, topSpeed);
}
2. Click the Quick Actions light bulb under the red squiggle, and then click Generate constructor in
'Automobile'.
In the Automobile class file, notice that the new constructor has examined the names of the local variables
that are used in the constructor call, found properties that have the same names in the Automobile class, and
supplied code in the constructor body to store the argument values in the Model and TopSpeed properties.
3. After you generate the new constructor, a wavy underline appears under the call to the default constructor in
DefaultAutomobileIsInitializedCorrectly . The error message states that the Automobile class has no
constructor that takes zero arguments. To generate an explicit default constructor that does not have
parameters, click the Quick Actions light bulb, and then click Generate constructor in 'Automobile'.
To generate a stub for a method
Assume that the specification states that a new Automobile can be put into a Running state if its Model and
TopSpeed properties are set to something other than the default values.
myAuto.Start();
Assert.IsTrue(myAuto.IsRunning == true);
myAuto.Start()
Assert.IsTrue(myAuto.IsRunning = True)
2. Click the Quick Actions light bulb for the myAuto.Start method call and then click Generate method
'Automobile.Start'.
3. Click the Quick Actions light bulb for the IsRunning property and then click Generate property
'Automobile.IsRunning'.
The Automobile class now contains a method named Start() and a property named IsRunning .
To run the tests
1. On the Test menu, choose Run, All Tests.
The Run, All Tests command runs all the tests in any test frameworks that are written for the current
solution. In this case, there are two tests, and they both fail, as expected. The
DefaultAutomobileIsInitializedCorrectly test fails because the Assert.IsTrue condition returns False . The
AutomobileWithModelNameCanStart test fails because the Start method in the Automobile class throws an
exception.
The Test Results window is shown in the following illustration.
2. In the Test Results window, double-click on each test result row to go to the location of each test.
To implement the source code
1. Add the following code to the default constructor so that the Model , TopSpeed and IsRunning properties
are all initialized to their correct default values of "Not specified" , -1 , and False (or false for C#).
public Automobile()
{
this.Model = "Not specified";
this.TopSpeed = -1;
this.IsRunning = false;
}
Sub New()
Model = "Not specified"
TopSpeed = -1
IsRunning = False
End Sub
2. When the Start method is called, it should set the IsRunning flag to true only if the Model or TopSpeed
properties are set to something other than their default value. Remove the NotImplementedException from
the method body and add the following code.
See Also
Generate From Usage
Writing Code
Using IntelliSense
Unit Test Your Code
Quick Actions
JavaScript IntelliSense
10/18/2017 • 4 min to read • Edit Online
Visual Studio 2017 provides a powerful JavaScript editing experience right out of the box. Powered by a TypeScript
based language service, Visual Studio delivers richer IntelliSense, support for modern JavaScript features, and
improved productivity features such as Go to Definition, refactoring, and more.
NOTE
The JavaScript language service in Visual Studio 2017 uses a new engine for the language service ("salsa"). Details are
included here in this topic, and you might also want to read this blog post. The new editing experience also mostly applies in
VS Code. See the VS Code docs for more info.
For more information about the general IntelliSense functionality of Visual Studio, see Using IntelliSense.
nextItem = "box";
nextItem; // now we know nextItem is a string
For a function, the return type can be inferred from the return statements.
For function parameters, there is currently no inference, but there are ways to work around this using JSDoc or
TypeScript .d.ts files (see later sections).
Additionally, there is special inference for the following:
"ES3-style" classes, specified using a constructor function and assignments to the prototype property.
CommonJS-style module patterns, specified as property assignments on the exports object, or assignments to
the module.exports property.
function Foo(param1) {
this.prop = param1;
}
Foo.prototype.getIt = function () { return this.prop; };
// Foo will appear as a class, and instances will have a 'prop' property and a 'getIt' method.
exports.Foo = Foo;
// This file will appear as an external module with a 'Foo' export.
// Note that assigning a value to "module.exports" is also supported.
/**
* @type {{a: boolean, b: boolean, c: number}}
*/
var x = {a: true};
x.b = false;
x. // <- "x" is shown as having properties a, b, and c of the types specified
As mentioned, function parameters are never inferred. However, using the JSDoc @param tag you can add types to
function parameters as well.
/**
* @param {string} param1 - The first argument to this function
*/
function Foo(param1) {
this.prop = param1; // "param1" (and thus "this.prop") are now of type "string".
}
NOTE
This feature is disabled by default if using a tsconfig.json configuration file, but may be set to enabled as outlined
further below).
Currently auto-detection works for dependencies downloaded from npm (by reading the package.json file), Bower
(by reading the bower.json file), and for loose files in your project that match a list of roughly the top 400 most
popular JavaScript libraries. For example, if you have jquery-1.10.min.js in your project, the file jquery.d.ts will
be fetched and loaded in order to provide a better editing experience. This .d.ts file will have no impact on your
project.
If you do not wish to use auto-acquisition, disable it by adding a configuration file as outlined below. You can still
place definition files for use directly within your project manually.
Visual C++ Intellisense
10/18/2017 • 4 min to read • Edit Online
In Visual Studio 2015, IntelliSense is available for single code files as well as for files in projects. In cross-platform
projects, some IntelliSense features are available in .cpp and .c files in the shared code project even when you are in
an Android or iOS context.
You can use the menu items and keyboard shortcuts shown in the following image to access IntelliSense.
Statement completion and member list
When you start typing a keyword, type, function, variable name, or other program element that the compiler
recognizes, the editor offers to complete the word for you
For a list of the icons and their meanings, see Class View and Object Browser Icons.
The first time member list is invoked it only shows members that are accessible for the current context. If you use
Ctrl + J after that, it shows all members regardless of accessibility. If you invoke it a third time, an even wider list of
program elements is shown. You can turn off statement completion in the C/C++ General Options page.
Parameter Help
When you type an opening brace of a function call, or angle bracket on a class template variable declaration, the
editor shows a small window with the parameter types for each overload of the function or constructor. The
"current" parameter--based on the cursor location--is in bold. You can turn off Statement completion in the C/C++
General Options page.
Quick Info
When you hover the mouse cursor over a variable, a small window appears inline that shows the type information
and the header in which the type is defined. Hover over a function call to see the function's signature. You can turn
off Quick Info in the Text Editor, C/C++, Advanced page.
Error squiggles
Squiggles under a program element (variable, keyword, brace, type name, and so on) call your attention to an error
or potential error in the code. A green squiggle appears when you write a forward declaration, to remind you that
you still need to write the implementation. A purple squiggle appears in a shared project when there is an error in
code that is not currently active, for example when you are working in the Windows context but enter something
that would be an error in an Android context. A red squiggle indicates a compiler error or warning in active code
that you need to deal with.
Cross-Platform IntelliSense
In a shared code project, some IntelliSense features such as squiggles are available even when you are working in
an Android context. If you write some code that would result in an error in an inactive project, IntelliSense still
shows squiggles, but they are in a different color than squiggles for errors in the current context.
Here's an OpenGLES Application that is configured to build for Android and iOS. The illustration shows shared code
being edited. In the first image, Android is the active project:
By default, single file IntelliSense only uses standard include directories to find header files. To add additional
directories, open the shortcut menu on the Solution node, and add your directory to Debug Source Code list, as
the following illustration shows:
See Also
Using IntelliSense
Supplying XML Code Comments
10/18/2017 • 1 min to read • Edit Online
You can make the comments in source code files available as IntelliSense. When you add the /doc switch to the
Visual Basic, C#, or C++ compiler command line, an .xml file is generated that serves as the basis for IntelliSense
documentation.
For more information about documenting code in Visual Basic, see see How to: Create XML Documentation.
For more information about documenting code in C#, see XML Documentation Comments.
For more information about documenting code in C++, see Comments and XML Documentation.
See Also
Using IntelliSense
Navigating Code
10/18/2017 • 5 min to read • Edit Online
Visual Studio provides numerous ways to navigate code in the editor. This topic summarizes the different ways
you can navigate your code, and provides links to topics that go into more detail.
Navigation bar
You can use the navigation bar (the drop-down boxes at the top of the code window) to navigate to code in a
codebase. You can choose a type or member to go directly to it. The navigation bar appears when you edit code in
a Visual Basic, C#, or C++ code base. In a partial class, members defined outside the current code file may be
disabled (they appear in grey).
You can navigate around the drop-down boxes as follows:
To navigate to another project that the current file belongs to, choose it in the left drop-down.
To navigate to a class or type, choose it in the middle drop-down.
To navigate directly to a procedure or other member of a class, choose it in the right drop-down.
To shift focus from the code window to the navigation bar, press the shortcut key combination Ctrl + F2.
To shift focus from box to box on the navigation bar, press the Tab key.
To select the navigation bar item that has focus and return to the code window, press the Enter key.
To return focus from the navigation bar to the code without selecting anything, press the Esc key.
To hide the navigation bar, change the Navigation bar option in the Text Editor All Languages settings (Tools,
Options, Text Editor, All Languages), or you can change the settings for individual languages.
INPUT FUNCTION
Keyboard Place your text cursor somewhere inside the type name, and
press Shift + F12
Reference highlighting
When you click a symbol in the source code, all instances of that symbol are highlighted in the document. The
highlighted symbols may include declarations and references, and many other symbols that Find All References
would return. These include the names of classes, objects, variables, methods, and properties. In Visual Basic code,
keywords for many control structures are also highlighted. To move to the next or the previous highlighted
symbol, press Ctrl + Shift + DOWN ARROW or Ctrl + Shift + UP ARROW. You can change the highlighting
color in Tools, Options, Environment, Fonts and Colors, Highlighted Reference.
Go To commands
Go To has the following commands, which are available in the Edit menu under Go To:
Go To Line (Ctrl + G): Move to the specified line number in the active document.
Go to All (Ctrl + T or Ctrl + ,): Move to the specified line, type, file, member, or symbol.
Go to File (Ctrl + 1, Ctrl + F): Move to the specified file in the solution.
Go to Type (Ctrl + 1, Ctrl + T): Move to the specified type in the solution.
Go to Member (Ctrl + 1, Ctrl + M): Move to the specified member in the solution.
Go to Symbol (Ctrl + 1, Ctrl + S): Move to the specifed symbol in the solution.
See more about these commands in the Find code using Go To commands topic.
Go To Definition
Go To Definition takes you to the definition of the selected element. For more information, see Go To Defintion and
Peek Definition.
INPUT FUNCTION
Keyboard Place your text cursor somewhere inside the type name, and
press F12
Peek Definition
Peek Definition displays the definition of the selected element in a window without navigating away from your
current location in the code editor. For more information, see How to: View and Edit Code by Using Peek Definition
and Go To Defintion and Peek Definition.
INPUT FUNCTION
Keyboard Place your text cursor somewhere inside the type name, and
press Alt + F12
Go To Implementation
Using Go To Implementation, you can navigate from a base class or type to its implementations. If there are
multiple implementations, you will see them listed in the Find Symbol Results window:
INPUT FUNCTION
Keyboard Place your text cursor somewhere inside the type name, and
press Ctrl + F12
Call Hierarchy
Call Hierarchy shows you the calls to a method in the Call Hierarchy window:
INPUT FUNCTION
Keyboard Place your text cursor somewhere inside the type name, and
press Ctrl + K, Ctrl + T
Structure Visualizer
The Structure Visualizer feature in the code editor shows structure guide lines - vertical dashed lines that indicate
matching curly braces in your codebase. This makes it easier to see where logical blocks begin and end.
To disable structure guide lines, go to Tools, Options, Text Editor, General and clear the Show structure guide
lines box.
CodeLens information
You can find info about specific code, like changes and who made those changes, references, bugs, work items,
code reviews, and unit test status when you use CodeLens in the code editor. CodeLens works like a heads-up
display when you use Visual Studio Enterprise with Team Foundation Server. See Find code changes and other
history.
See Also
Writing code in the code and text editor
Finding references in your code
10/18/2017 • 2 min to read • Edit Online
You can use the Find All References command to find where particular code elements are referenced throughout
your codebase. The Find All References command is available on the context (right-click) menu of the element
you want to find references to. Or, if you are a keyboard user, press Shift + F12.
The results appear in a tool window named 'element' references, where element is the name of the item you are
searching for. A toolbar in the references window enables you to:
Change the scope of the search in a drop-down list box. You can choose to look only in changed documents all
the way up to the entire solution.
Copy the selected referenced item by choosing the Copy button.
Choose buttons to go to the next or previous location in the list, or press the F8 and Shift + F8 keys to do so.
Remove any filters on the returned results by choosing the Clear All Filters button.
Change how returned items are grouped by choosing a setting in the Group by: drop-down list box.
Keep the current search results window by choosing the Keep Results button. When you choose this button,
the current search results stay in this window, and new search results appear in a new tool window.
Search for strings within the search results by entering text in the Search Find All References text box.
You can also hover the mouse over any search result to see a preview of the reference.
Navigate to references
You can use the following methods to navigate to references in the references window:
Press F8 to go to the next reference, or Shift + F8 to go to the previous reference.
Press the Enter key on a reference, or double-click it, to go to it in code.
On the context menu of a reference, choose the Go To Previous Location or Go To Next Location
commands.
Choose the UP arrow and DOWN arrow keys (if they are enabled in the Options dialog box). To enable this
functionality, on the menu bar, choose Tools, Options, Environment, Tabs and Windows, Preview Tab, and
then select the Allow new files to be opened in the preview tab and Preview selected files in Find
Results boxes.
Change reference groupings
By default, references are grouped by project, then by definition. However, you can change this grouping order by
changing the setting in the Group by: drop-down list box on the toolbar. For example, you can change it from the
default setting of Project then definition to Definition then project, as well to other settings.
Definition and Project are the two default groupings used, but you can add others by choosing the Grouping
command on the selected item's context menu. Adding more groupings can be helpful if your solution has a lot of
files and paths.
See also
Navigating Code
Go To Definition and Peek Definition
10/18/2017 • 1 min to read • Edit Online
The Go To Definition and Peek Definition features enable you to easily view the definition of a type or member.
Go To Definition
The Go To Definition feature navigates to the source of a type or member, and opens the result in a new tab. If you
are a keyboard user, place your text cursor somewhere inside the symbol name and press F12. If you are a mouse
user, either select Go To Definition from the context menu or use the Ctrl-click functionality described below.
Ctrl-click Go To Definition
In Visual Studio 2017 version 15.4, there's an easier way for mouse users to quickly access Go To Definition.
Symbols become clickable when you press Ctrl and hover over the type or member. To quickly navigate to the
definition of a symbol, press the Ctrl key and then click on it. It's that easy!
You can change the modifier key for mouse-click Go To Definition by going to Tools, Options, Text Editor,
General, and selecting either Alt or Ctrl+Alt from the Use modifier key drop-down. You can also disable
mouse-click Go To Definition by unchecking the Enable mouse click to perform Go To Definition checkbox.
Peek Definition
The Peek Definition feature lets you preview the definition of a type without leaving your current location in the
editor. If you are a keyboard user, place your text cursor somewhere inside the type or member name and press
Alt + F12. If you are a mouse user, you can select Peek Definition from the context menu. In Visual Studio 2017
version 15.4 and later, there is a new way to peek view a definition by using the mouse. First, go to Tools,
Options, Text Editor, General. Select the option Open definition in peek view and click OK to close the
Options dialog box.
Then, press Ctrl (or whichever modifier key is selected in Options), and click on the type or member.
If you peek another definition from the popup window, you will start a breadcrumb path which you can navigate
using the circles and arrows which appear above the popup.
For more information, see How to: View and Edit Code by Using Peek Definition (Alt+F12).
See Also
Navigating Code
How to: View and Edit Code by Using Peek Definition (Alt+F12)
How to: View and Edit Code by Using Peek
Definition (Alt+F12)
10/18/2017 • 3 min to read • Edit Online
You can use the Peek Definition command to view and edit code without switching away from the code that
you're writing. Peek Definition and Go To Definition show the same information, but Peek Definition shows it
in a pop-up window, and Go To Definition shows the code in a separate code window. Go To Definition causes
your context (that is, the active code window, current line, and cursor position) to switch to the definition code
window. By using Peek Definition, you can view and edit the definition and move around inside the definition file
while keeping your place in the original code file.
You can use Peek Definition with C#, Visual Basic, and C++ code. In Visual Basic, Peek Definition shows a link
to the Object Browser for symbols that don't have definition metadata (for example, .NET Framework types that
are built in).
The definition window appears below the printer.Print("Hello World!") line in the original file. The
window doesn't hide any of the code in your original file. The lines that follow
printer.Print("Hello World!") appear under the definition window.
2. You can move the cursor to different locations in the code definition window. You can also still move
around in the original code window.
3. You can copy a string from the definition window and paste it in the original code. You can also drag and
drop the string from the definition window to the original code without deleting it from the definition
window.
4. You can close the definition window by choosing the Esc key or the Close button on the definition window
tab.
To open a Peek Definition window from within a Peek Definition window
If you already have a Peek Definition window open, you can call Peek Definition again on the code in
that window. Another definition window opens. A set of breadcrumb dots appears next to the definition
window tab, which you can use to navigate between definition windows. The tooltip on each dot shows the
file name and path of the definition file that the dot represents.
NOTE
You can also use the same keyboard shortcuts to edit code in a Peek Definition window as you use elsewhere in
Visual Studio.
See Also
Navigating Code
Go To Defintion and Peek Definition
Productivity Tips
Find code using Go To commands
10/18/2017 • 2 min to read • Edit Online
Visual Studio's Go To commands perform a focused search of your code to help you quickly find specified items.
You can go to a specific line, type, symbol, file, and member from a simple, unified interface. This feature exists in
Visual Studio 2017 and later.
How to use it
INPUT FUNCTION
This will display a small window at the top right of your code editor, by default.
As you type in the text box, the results appear in a drop-down list below the text box. To go to an element, choose it
in the list.
You can also enter a question mark (?) to get additional help.
Filtered Searches
By default, the specified item is searched for in all solution items. However, you can limit your code search to
specific element types by prefacing the search terms with certain characters. You can also quickly change the
search filter by choosing buttons on the Go To dialog box toolbar. Buttons that change the type filters are on the
left side, and buttons that change the scope of the search are on the right side.
ICON DESCRIPTION
Camel casing
If you use camel casing in your code, you can find code elements faster by entering only the capital letters of the
code element name. For example, if your code has a type called CredentialViewModel , you can narrow down the
search by choosing the Type filter ("t") and then entering just the capital letters of the name ( CVM ) in the Go To
dialog box. This feature can be helpful if your code has long names.
Settings
Selecting the gear icon lets you change how this feature works:
SETTING DESCRIPTION
Use preview tab Display the selected item immediately in the IDE's preview tab
Show details Display project, file, line, and summary information from
documentation comments in the window
Center window Move this window to the top-center of the code editor,
instead of the top-right
See Also
Navigating Code
Go To Definition and Peek Definition
Customizing the Editor
10/18/2017 • 1 min to read • Edit Online
You can customize the formatting, tabs, fonts and colors, IntelliSense, and many other features of the editor in
general or a specific language editor by changing options. For more information about these options, see Text
Editor Options Dialog Box or type Editor into QuickLaunch. You can also change how editor windows are
displayed.
In This Section
These topics explain how to adjust the appearance and behavior of the Text and Code editor.
How to: Change Text Case in the Editor
Explains how to change text case in your code.
How to: Manage Editor Windows
Shows how to manipulate editor windows.
How to: Manage Editor Modes
Explains how to use the full screen and virtual spaces modes.
See Also
Writing Code
Setting Bookmarks in Code
General, Environment, Options Dialog Box
Documents, Environment, Options Dialog Box
Fonts and Colors, Environment, Options Dialog Box
How to: Change Text Case in the Editor
10/18/2017 • 1 min to read • Edit Online
You can use menu commands or keyboard shortcuts to convert the case of selected text to all upper case or to all
lower case.
NOTE
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Personalize the Visual Studio IDE.
Procedure
To switch text to upper case
1. Select the text you want to convert.
2. On the Edit menu, select Advanced.
3. To convert text to all upper case, choose Make Uppercase, or press CTRL+SHIFT+U.
— or —
To convert text to all lower case, choose Make Lowercase, or press CTRL+U.
TIP
To revert to the previous case formatting before this change, select Undo from the Edit menu.
See Also
Customizing the Editor
Text Editor Options Dialog Box
Writing Code
How to: Manage Editor Modes
10/18/2017 • 1 min to read • Edit Online
You can display the Visual Studio Code Editor in various display modes.
NOTE
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Personalize the Visual Studio IDE.
NOTE
Virtual Space is enabled in Column Selection mode. When Virtual Space mode is not enabled, the insertion point
moves from the end of one line directly to the first character of the next.
See Also
Customizing the Editor
Customize window layouts in Visual Studio
Fonts and Colors, Environment, Options Dialog Box
How to: Manage Editor Windows
10/18/2017 • 1 min to read • Edit Online
You can work on code in several locations at once. Do this by splitting an Editor window, or by opening several
instances of editor windows.
NOTE
Not all editor windows support multiple instances.
TIP
To make one pane larger than the other, drag the splitter bar upward or downward.
See Also
Customizing the Editor
Writing Code
Customizing window layouts
Develop code in Visual Studio without projects or
solutions
10/18/2017 • 8 min to read • Edit Online
In Visual Studio 2017, you can open code from nearly any type of directory-based project into Visual Studio
without the need for a solution or project file. This means you can, for example, find a code project on Git, clone it,
and then open it directly into Visual Studio and begin developing without having to create a solution or project.
Not only can you edit the code and build it in Visual Studio, you can also navigate through your code (such as by
using the Navigate To command). Code will appear with syntax colorization and, in many cases, include basic
statement completion and debugging, complete with breakpoints. Some languages will include even more
functionality. See Create portable, custom editor settings for more information.
3. In Visual Studio, choose the Team Explorer tab to open Team Explorer.
4. In Team Explorer, under the Local Git Repositories section, choose the Clone command and then paste
the URL of the GitHub page into the text box.
5. Choose the Clone button to clone the project's files to a local Git repository. Depending on the size of the
repo, this process could take several minutes.
6. After the repo has been cloned to your system, in Team Explorer, choose the Open command on the
context (right-click) menu of the newly cloned repo.
7. Choose the Show Folder View command to view the files in Solution Explorer
You can now browse folders and files in the cloned repo, and view and search the code in the Visual Studio
code editor, complete with syntax colorization and other features.
Choosing Configure Tasks opens a file called tasks.vs.json. If this file doesn't exist, it is created. This file
contains the build tasks for the selected file or folder.
2. Add the following build task to tasks.vs.json. For this example, we'll add a simple task called "List outputs"
that lists files and subfolders of the selected folder in the Output window. (The new task should be added
within the existing "tasks" array.)
{
"taskName": "List outputs",
"appliesTo": "*",
"type": "command",
"command": "${env.COMSPEC}",
"args": [
"dir ${outDir}"
]
},
{
"taskName": "makefile-build",
"appliesTo": "makefile",
"type": "command",
"contextType": "build",
"command": "nmake"
},
{
"taskName": "makefile-clean",
"appliesTo": "makefile",
"type": "command",
"contextType": "clean",
"command": "nmake",
"args": [
"clean"
]
},
Now that you have associated custom build commands with the file, you can designate the file as the
startup item.
5. On the file's context menu, choose Set as Startup Item.
6. On the toolbar, choose the dropdown arrow next to the Start button. The startup item now appears as an
option.
You can now choose the Start button or the F5 key to run your codebase. You can edit and debug your codebase
in Visual Studio even though Visual Studio doesn't recognize the build tools of the codebase. Output from the
build task appears in the Output window, and build errors appear in the Error List. The tasks.vs.json build task file
couples the Visual Studio inner development loop to the custom build tools used by your codebase.
Custom build tasks can be added to individual files or to all files of a specific type. For instance, NuGet package
files can be configured to have a "Restore Packages" task, or all source files can be configured to have a static
analysis task, such as a linter for all .js files.
Visual Studio supports the VSCode $variable substitution in the root of tasks.vs.json, in addition to environment
variables (such as $env.var ) or keys.
Specifying the output location notifies Visual Studio where to find the project's build output.
See also
Writing code in the code and text editor
Create portable, custom editor settings with
EditorConfig
10/19/2017 • 3 min to read • Edit Online
Text editor settings in Visual Studio apply to all projects of a given type. So, for example, if you change a C# text
editor setting, that setting applies to all C# projects in Visual Studio. However, in some cases, you may need to use
conventions that differ from your own personal editor preferences. EditorConfig files enable you to do this by
providing common text editor options on a per-project basis. EditorConfig settings, which are contained in an
.editorconfig file added to your codebase, supersede global Visual Studio text editor settings. This means that you
can tailor each codebase to use the text editor settings you prefer. No plug-in is required to use this functionality in
Visual Studio.
Coding consistency
Settings in EditorConfig files enable you to maintain consistent coding styles and settings for a language, such as
indent style, tab width, end of line characters, encoding, and more, in a codebase regardless of the editor or IDE you
use. For example, when coding in C#, if your codebase has a convention to prefer that indents always consist of five
space characters, documents use UTF-8 encoding, and each line always ends with a CR/LF, you can configure an
.editorconfig file to do that.
Coding conventions you use on your personal projects may differ from those used on your team's projects. For
example, you might prefer that when you're coding, pressing the Tab key adds a TAB character. However, your
team might prefer that indenting adds four space characters instead of a TAB character. EditorConfig files resolve
this problem by enabling you to have a configuration for each scenario.
Because the settings are contained in a file in the codebase, they travel along with that codebase. As long as you
open the code file in an EditorConfig-compliant editor, the text editor settings are implemented. For more
information about EditorConfig files, see the EditorConfig.org website. If you edit a lot of .editorconfig files, you
may find the EditorConfig Language Service extension helpful.
The new .editorconfig file settings will apply to the level in which it is located and all its subfiles.
Supported settings
The editor in Visual Studio supports the following from the core set of EditorConfig properties:
indent_style
indent_size
tab_width
end_of_line
charset
root
In addition, it supports the .NET code style conventions.
EditorConfig settings are supported in all Visual Studio-supported languages except for XML.
Example
Here is an example that shows the indent state of a C# code snippet before and after adding a .editorconfig file to
the project. The Tabs setting in the Options dialog box for the Visual Studio text editor is set to produce space
characters when you press the Tab key in your code.
As expected, pressing the Tab key on the next line indents the line by adding four additional white space
characters.
We'll add a new file called .editorconfig to the project, with the following contents. The [*.cs] setting means that
this change will apply only to .cs files in this project.
Now, when you press the Tab key, you get tab characters instead of spaces.
NOTE
Adding a .editorconfig file to your project or codebase will not convert the existing styles to the new ones, it will only apply to
newly-added lines. If you remove a .editorconfig file from your project or codebase, you must reload the code file(s) for the
editor settings to revert back to global settings. Any errors in .editorconfig files are reported in the Error window in Visual
studio.
See Also
Create Portable Custom Editor Options with EditorConfig
How to: Track Your Code by Customizing the
Scrollbar
10/18/2017 • 2 min to read • Edit Online
When you are working with long code files, it can be hard to keep everything in mind. You can customize the scroll
bar of the code window to give you a bird's eye view of what's happening in your code.
To show annotations on the scroll bar
1. You can set up the scroll bar to show code changes, breakpoints, errors, and bookmarks.
Open the Scroll Bar options page (Tools, Options Text Editor. All Languages or a specific language, or
type scroll bar in the Quick Launch window).
2. Select Show Annotations over vertical scroll bar, then select the annotations you want to see. (The
Marks option includes breakpoints and bookmarks.)
3. Now try it out. Open a large code file and replace something that occurs in several places in the file. The
scroll bar shows you the effect of the replacements, so you can back out your changes if you replaced
something you shouldn't have.
Here's how the scroll bar looks after a search for a string. Notice that all instances of the string appear.
Here's the scroll bar after replacing all the instances of the string. You can see immediately that the
operation caused some problems.
To set the display mode for the scroll bar
1. The scroll bar has two modes, bar mode (the default) and map mode. Bar mode just displays annotation
indicators on the scroll bar. In map mode the lines of code are represented on the scroll bar. You can choose
how wide they are and whether they show the underlying code when you rest the pointer on them. When
you click a location on the scroll bar, the cursor moves to that location in the code. Collapsed regions are
shaded differently; they are expanded when you double-click them.
On the Scroll Bar options page, select either Use Bar mode for vertical scroll bar or Use Map mode for
vertical scroll bar. You can choose the width in the Source Overview dropdown.
Here's how the search example looks when map mode is on and the width is set to Medium:
2. In map mode, to enable previews of the code when you move the cursor up and down the scroll bar, select
the Show Preview Tooltip option. Here's how it looks:
If you want to keep the map mode scrolling behavior and the preview tooltip but don't want to see the
source code overview, you can set Source Overview to Off.
Code Snippets
10/18/2017 • 2 min to read • Edit Online
Code snippets are small blocks of reusable code that can be inserted in a code file using a context menu command
or a combination of hotkeys. They typically contain commonly-used code blocks such as try-finally or if-else
blocks, but they can be used to insert entire classes or methods.
try
{
}
finally
{
You can insert this snippet by clicking Insert Snippet in the context menu of the code window, then Visual C#,
then type tryf , then TAB, or you can type tryf and press TAB + TAB.
An example of a surround-with snippet: in C++ the shortcut if can be used either as an insertion snippet or as a
surround-with snippet. If you select a line of code (for example return FALSE; ), and then click Surround With,
then if, the snippet is expanded around the line:
if (true)
{
return FALSE;
}
If you change newPropertyValue to m_property , then every instance of newPropertyValue is changed. If you
change String to Int in the property declaration, then the value in the set method is also changed to Int .
See Also
Walkthrough: Creating a Code Snippet
How to: Distribute Code Snippets
Best Practices for Using Code Snippets
Troubleshooting Snippets
Visual C# Code Snippets
Visual C++ Code Snippets
Code Snippets Schema Reference
Walkthrough: Creating a Code Snippet
10/18/2017 • 5 min to read • Edit Online
You can create a code snippet with only a few steps. All you need to do is create an XML file, fill in the appropriate
elements, and add your code to it. You can also add references and replacement parameters to your code. You can
add the snippet to your Visual Studio installation by using the Import button on the Code Snippets Manager
(Tools, Code Snippets Manager...).
Snippet Template
The following is the basic snippet template:
<Code Language="VB">
<![CDATA[Console.WriteLine("Hello, World!")]]>
</Code>
6. Test your snippet by opening a Visual Basic project and opening a code file. In the file click Insert Snippet
on the context menu, then My Code Snippets. You should see a snippet named My Visual Basic Code
Snippet. Double-click it.
7. You should see Console.WriteLine("Hello, World!") inserted in the code.
Adding Description and Shortcut Fields
1. Description fields give more information about your code snippet when viewed in the Code Snippets
Manager. The shortcut is a tag that users can type in order to insert your snippet. Edit the snippet you have
added by opening the file
%USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\Visual Basic\My Code
Snippet\VBCodeSnippet.snippet
.
2. Add Author and Description elements to the Header element, and fill them in.
3. The Header element should look something like this:
<Header>
<Title>Hello World VB</Title>
<Author>Myself</Author>
<Description>Says Hello to the world.</Description>
</Header>
4. Open the Code Snippets Manager and select your code snippet. In the right pane you should see that the
Description and Author fields are now populated.
5. To add a shortcut, add a Shortcut element alongside the Author and Description element:
<Header>
<Title>Hello World VB</Title>
<Author>Myself</Author>
<Description>Says Hello to the world.</Description>
<Shortcut>hello</Shortcut>
</Header>
<Imports>
<Import>
<Namespace>System.Windows.Forms</Namespace>
</Import>
</Imports>
<![CDATA[MessageBox.Show("Hello, World!")]]>
Imports System.Windows.Forms
9. Look at the project's properties. The References tab includes a reference to System.Windows.Forms.dll.
Adding Replacements
1. You may want parts of your code snippets to be replaced by the user, for example if you add a variable and
want the user to replace the variable with one in the current project. You can provide two types of
replacements: literals and objects. Literals are strings of some type (string literals, variable names, or string
representations of numeric values). Objects are instances of some type other than a string. In this procedure
you will declare a literal replacement and an object replacement, and change the code to reference these
replacements.
2. Open your snippet.
3. This example uses a SQL connection string, so you need to change the Imports and References elements to
add the appropriate references:
<References>
<Reference>
<Assembly>System.Data.dll</Assembly>
</Reference>
<Reference>
<Assembly>System.Xml.dll</Assembly>
</Reference>
</References>
<Imports>
<Import>
<Namespace>System.Data</Namespace>
</Import>
<Import>
<Namespace>System.Data.SqlClient</Namespace>
</Import>
</Imports>
4. To declare a literal replacement for the SQL connection string, add a Declarations element under the
Snippet element, and in it add a Literal element with subelements for the ID, the tooltip, and the default
value for the replacement:
<Declarations>
<Literal>
<ID>SqlConnString</ID>
<ToolTip>Replace with a SQL connection string.</ToolTip>
<Default>"SQL connection string"</Default>
</Literal>
</Declarations>
5. To declare an object replacement for the SQL connection, add an Object element inside the Declarations
element, and add sub-elements for the ID, the type of the object, the tooltip, and the default value. The
resulting Declarations element should look like this:
<Declarations>
<Literal>
<ID>SqlConnString</ID>
<ToolTip>Replace with a SQL connection string.</ToolTip>
<Default>"SQL connection string"</Default>
</Literal>
<Object>
<ID>SqlConnection</ID>
<Type>System.Data.SqlClient.SqlConnection</Type>
<ToolTip>Replace with a connection object in your application.</ToolTip>
<Default>dcConnection</Default>
</Object>
</Declarations>
6. In the code section, you reference the replacements with surrounding $ signs, for example $replacement$ :
See Also
Code Snippets Schema Reference
How to: Distribute Code Snippets
10/18/2017 • 3 min to read • Edit Online
You can simply give your code snippets to your friends and have them install the snippets on their own computers
by using the Code Snippets Manager. However, if you have several snippets to distribute or would like to distribute
them more widely, you include your snippet file in a Visual Studio extension, which Visual Studio users can install.
You must install the Visual Studio SDK in order to create Visual Studio extensions. Find the version of the VSSDK
that matches your Visual Studio installation at Visual Studio Downloads.
// Visual Basic
[$RootKey$\Languages\CodeExpansions\Basic\Paths]
"HelloWorldVB"="$PackageFolder$"
If you examine this key, you can see how to specify different languages.
3. Select the .pkgdef file in the Solution Explorer, and in the Properties window make sure Build Action is set
to Content, Copy to Output Directory is set to Copy always, and Include in VSIX is set to true.
4. Add the .pkgdef file as an asset in the VSIX manifest. In the source.extension.vsixmanifest file, go to the
Assets tab and click New.
5. In the Add New Asset dialog, set the Type to Microsoft.VisualStudio.VsPackage, the Type to File on
filesystem, and the Path to HelloWorldVB.pkgdef (which should appear in the dropdown).
Testing the Snippet
1. Now you can make sure that the code snippet works in the experimental instance of Visual Studio. The
experimental instance is a second copy of Visual Studio that is separate from the one you use to write code.
It allows you to work on an extension without affecting your development environment.
2. Build the project and start debugging. A second instance of Visual Studio should appear.
3. In the experimental instance, go to Tools / Code Snippets Manager and set the Language to Basic. You
should see HelloWorldVB as one of the folders, and you should be able to expand the folder to see the
HelloWorldVB snippet.
4. Test the snippet. In the experimental instance, open a Visual Basic project and open one of the code files.
Place your cursor somewhere in the code, right-click, and on the context menu select Insert Snippet.
5. You should see HelloWorldVB as one of the folders. Double-click it. You should see a pop-up Insert
Snippet: HellowWorldVB > that has a dropdown HelloWorldVB. Click the HelloWorldVB dropdown. You
should see the following line added to the file:
Console.WriteLine("Hello, World!")
See Also
Code Snippets
Visual C# Code Snippets
10/18/2017 • 4 min to read • Edit Online
Code snippets are ready-made snippets of code you can quickly insert into your code. For example, the for code
snippet creates an empty for loop. Some code snippets are surround-with code snippets, which enable you to
select lines of code, and then choose a code snippet which incorporates the selected lines of code. For example,
when you select lines of code and then activate the for code snippet, it creates a for loop with those lines of
code inside the loop block. Code snippets can make writing program code quicker, easier, and more reliable.
You can insert a code snippet at the cursor location, or insert a surround-with code snippet around the currently
selected code. The Code Snippet Inserter is invoked through the Insert Code Snippet or Surround With
commands on the IntelliSense menu, or by using the keyboard shortcuts CTRL+K and then X or CTRL+K and
then S respectively.
The Code Snippet Inserter displays the code snippet name for all available code snippets. The Code Snippet
Inserter also includes an input dialog box where you can type the name of the code snippet, or part of the code
snippet name. The Code Snippet Inserter highlights the closest match to a code snippet name. Pressing TAB at any
time will dismiss the Code Snippet Inserter and insert the currently selected code snippet. Typing ESC or clicking
the mouse in the Code Editor will dismiss the Code Snippet Inserter without inserting a code snippet.
attribute Creates a declaration for a class that Inside a namespace (including the
derives from Attribute. global namespace), a class, or a struct.
exception Creates a declaration for a class that Inside a namespace (including the
derives from an exception (Exception by global namespace), a class, or a struct.
default).
forr Creates a for loop that decrements the Inside a method, an indexer, a property
loop variable after each iteration. accessor, or an event accessor.
invoke Creates a block that safely invokes an Inside a method, an indexer, a property
event. accessor, or an event accessor.
See Also
Code Snippet Functions
Code Snippets
Template Parameters
How to: Use Surround-with Code Snippets
Visual C++ Code Snippets
10/18/2017 • 3 min to read • Edit Online
In Visual Studio, you can use code snippets to add commonly-used code to your C++ code files. In general, you can
use code snippets in much the same way as in C#, but the set of default code snippets is different.
You can either add a code snippet at a particular location in your code (insertion) or surround some selected code
with a code snippet.
#if 0
#endif // 0
#if 0
#include "pch.h" // or whatever line you had selected
#endif // 0
class MyClass
{
public:
MyClass();
~MyClass();
private:
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
The classi code snippet also provides the definition of a class named MyClass, but the default constructor and
destructor are defined inside the class definition:
class MyClass
{
public:
MyClass()
{
}
~MyClass()
{
}
private:
};
The foreach snippet provides a for each loop that iterates over the members of a collection:
for each (object var in collection_to_loop)
{
The forr snippet provides a reverse for loop in which the condition is based on the length (in integers) of an
object:
for (auto& i : v)
{
class SomeClass {
};
class SomeClass {
~SomeClass()
{
}
};
If you try to insert the destructor snippet outside a class, it provides a destructor with a placeholder name:
~TypeNamePlaceholder()
{
Code Snippet Functions
10/18/2017 • 1 min to read • Edit Online
There are three functions available to use with Visual C# code snippets. Functions are specified in the Function
element of the code snippet. For information on creating code snippets, see Code Snippets.
Functions
The following table describes the functions available for use with the Function element in code snippets.
Example
The following example shows how to use the GenerateSwitchCases function. When this snippet is inserted and an
enumeration is entered into the $switch_on$ literal, the $cases$ literal generates a case statement for every
value in the enumeration.
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>switch</Title>
<Shortcut>switch</Shortcut>
<Description>Code snippet for switch statement</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>expression</ID>
<ToolTip>Expression to switch on</ToolTip>
<Default>switch_on</Default>
</Literal>
<Literal Editable="false">
<ID>cases</ID>
<Function>GenerateSwitchCases($expression$)</Function>
<Default>default:</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
switch ($expression$)
{
$cases$
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Example
The following example shows how to use the ClassName function. When this snippet is inserted, the $classname$
literal is replaced with the name of the enclosing class at that location in the code file.
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Common constructor pattern</Title>
<Shortcut>ctor</Shortcut>
<Description>Code Snippet for a constructor</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<Default>int</Default>
</Literal>
<Literal>
<ID>name</ID>
<Default>field</Default>
</Literal>
<Literal default="true" Editable="false">
<ID>classname</ID>
<ToolTip>Class name</ToolTip>
<Function>ClassName()</Function>
<Default>ClassNamePlaceholder</Default>
</Literal>
</Declarations>
<Code Language="vjsharp" Format="CData">
<![CDATA[
public $classname$ ($type$ $name$)
{
this._$name$ = $name$;
}
private $type$ _$name$;
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Example
This example shows how to use the SimpleTypeName function. When this snippet is inserted into a code file, the
$SystemConsole$ literal will be replaced with the simplest form of the Console type in the context in which the
snippet was invoked.
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Console_WriteLine</Title>
<Shortcut>cw</Shortcut>
<Description>Code snippet for Console.WriteLine</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="false">
<ID>SystemConsole</ID>
<Function>SimpleTypeName(global::System.Console)</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
$SystemConsole$.WriteLine();
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
See Also
Function Element (Intellisense Code Snippets)
Code Snippets Schema Reference
How to: Use Surround-with Code Snippets
10/18/2017 • 1 min to read • Edit Online
The following procedures describe how to use surround-with code snippets. Surround-with code snippets are
available three ways: through a keyboard shortcut, through the Edit menu, and through the context menu.
To use surround-with code snippets through keyboard shortcut
1. In the Visual Studio IDE, open the file that you intend to edit.
2. In the Code Editor, select text to surround.
3. Type CTRL+K, CTRL+S.
4. Select the code snippet from the code snippet list using the mouse, or by typing the name of the code
snippet and pressing TAB or ENTER.
To use surround-with code snippets through the Edit menu
1. In the Visual Studio IDE, open the file that you intend to edit.
2. In the Code Editor, select text to surround.
3. From the Edit menu, select IntelliSense and then select the Surround With command.
4. Select the code snippet from the code snippet inserter and then press TAB or ENTER.
Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.
To use surround-with code snippets through the context menu
1. In the Visual Studio IDE, open the file that you intend to edit.
2. In the Code Editor, select text to surround.
3. Right-click the selected text and then select the Surround With command from the context menu.
4. Select the code snippet from the code snippet inserter and then press TAB or ENTER.
Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.
See Also
Visual C# Code Snippets
Code Snippet Picker
Best Practices for Using Code Snippets
10/18/2017 • 2 min to read • Edit Online
The code in a code snippet shows only the most basic way to do something. For most applications, the code must
be modified to suit the application.
Handling Exceptions
Typically, code snippet Try...Catch blocks catch and rethrow all exceptions. That may not be the right choice for your
project. For each exception, there are several ways to respond. For examples, see How to: Handle an Exception
Using try/catch (C# Programming Guide) and Try...Catch...Finally Statement.
File Locations
When you adapt file locations to your application, you should think about the following:
Finding an accessible location. Users may not have access to the Program Files folder of the computer, so
storing files with the application files may not work.
Finding a secure location. Storing files in the root folder (C:\) is not secure. For application data, we
recommend the \Application Data folder. For individual user data, the application can create a file for each
user in the \My Documents folder.
Using a valid file name. You can use the OpenFileDialog and SaveFileDialog controls to reduce the likelihood
of invalid file names. Be aware that between the time the user selects a file and the time your code
manipulates the file, the file may be deleted. In addition, the user may not have permissions to write to the
file.
Security
How secure a snippet is depends on where it is used in the source code and how it is modified once it is in the
code. The following list contains a few of the areas that must be considered.
File and database access
Code access security
Protecting resources (such as event logs, registry)
Storing secrets
Verifying inputs
Passing data to scripting technologies
For more information, see Securing Applications.
See Also
Visual Basic IntelliSense Code Snippets
Securing Applications
Code Snippets
Troubleshooting Snippets
10/18/2017 • 1 min to read • Edit Online
Problems with IntelliSense code snippets are typically caused by two problems: a corrupt snippet file or bad
content in the snippet file.
Common Problems
The Snippet Cannot Be Dragged from File Explorer to a Visual Studio Source File
The XML in the snippet file may be corrupt. The XML Editor in Visual Studio can locate problems in the XML
structure.
The snippet file may not conform to the snippet schema. The XML Editor in Visual Studio can locate
problems in the XML structure.
The Code Has Compiler Errors That Are Not Highlighted
You may be missing a project reference. Examine the documentation about the snippet. If the reference is
not found on the computer, you will need to install it. Inserting a snippet should add to the project any
references needed. If the snippet is missing the reference information, that can be reported to the snippet
creator as an error.
A variable may be undefined. Undefined variables in a snippet should be highlighted. If not, that can be
reported to the snippet creator as an error.
See Also
Code Snippets
Code Snippets Schema Reference
10/18/2017 • 17 min to read • Edit Online
IntelliSense Code Snippets are pre-authored pieces of code that are ready to be inserted into your application with
Visual Studio. You can increase productivity by providing code snippets that reduce the amount of time spent
typing repetitive code or searching for samples. You can use the IntelliSense Code Snippet XML schema to create
your own code snippets and add them to the code snippets that Visual Studio already includes.
Assembly Element
Specifies the name of the assembly referenced by the code snippet.
NOTE
The Assembly element is only supported by Visual Basic code snippets.
The text value of the Assembly element is either the friendly text name of the assembly, such as System.dll , or its
strong name, such as System,Version=1.0.0.1,Culture=neutral,PublicKeyToken=9b35aa323c18d4fb1 .
<Assembly>
AssemblyName
</Assembly>
PARENT ELEMENT DESCRIPTION
A text value is required. This text specifies the assembly that the code snippet references.
Author Element
Specifies the name of the snippet author. The Code Snippets Manager displays the name stored in the Author
element of the code snippet.
<Author>
Code Snippet Author
</Author>
A text value is required. This text specifies the author of the code snippet.
Code Element
Provides a container for short code blocks.
Two reserved words are available for use in the text of the Code element: $end$ and $selected$ . $end$ marks
the location to place the cursor after the code snippet is inserted. $selected$ represents text selected in the
document that is to be inserted into the snippet when it is invoked. For example, given a snippet that includes:
If the word "Blue" is selected when the user invokes the template, the result is:
You may not use either $end$ or $selected$ more than once in a code snippet. If you do, only the second
instance is recognized. Given a snippet that includes:
The initial space appears because there is a space between $selected$ and is .
All other $ keywords are dynamically defined in the <Literal> and <Object> tags.
<Code Language="Language"
Kind="method body/method decl/type decl/page/file/any"
Delimiter="Delimiter">
Code to insert
</Code>
ATTRIBUTE DESCRIPTION
Kind Optional attribute. Specifies the kind of code that the snippet
contains and the location at which a code snippet must be
inserted for the code snippet to compile. The values available
are method body , method decl , type decl , file , and
any .
method body Specifies that the code snippet is a method body, and
therefore, must be inserted inside a method declaration.
method decl Specifies that the code snippet is a method, and therefore,
must be inserted inside a class or module.
type decl Specifies that the code snippet is a type, and therefore, must
be inserted inside a class, module, or namespace.
file Specifies that the snippet is a full code file. These code
snippets can be inserted alone into a code file, or inside a
namespace.
any Specifies that the snippet can be inserted anywhere. This tag
is used for code snippets that are context-independent, such
as comments.
Snippet Element Contains the references, imports, declarations, and code for
the code snippet.
A text value is required. This text specifies the code, along with the literals and objects, that you can use when this
code snippet is inserted into a project.
CodeSnippet Element
Allows you to specify a heading and multiple IntelliSense Code Snippets, which you can insert into Visual Studio
code files.
<CodeSnippet Format="x.x.x">
<Header>... </Header>
<Snippet>... </Snippet>
</CodeSnippet>
ATTRIBUTE DESCRIPTION
Snippet Element Required element. Contains the code that will be inserted by
Visual Studio. There must be exactly one Snippet element in
a code snippet.
CodeSnippets Element
Groups CodeSnippet Elementelements. The CodeSnippets element is the root element of the code snippet XML
schema.
<CodeSnippets>
<CodeSnippet>... </CodeSnippet>
</CodeSnippets>
CodeSnippet Element Optional element. Parent element for all code snippet data.
There may be zero or more CodeSnippet elements in a
CodeSnippets element.
Declarations Element
Specifies the literals and objects that make up the parts of a code snippet that you can edit.
<Declarations>
<Literal>... </Literal>
<Object>... </Object>
</Declarations>
Literal Element Optional element. Defines the literals of the code snippet that
you can edit. There may be zero or more Literal elements
in a Declarations element.
Object Element Optional element. Defines the objects of the code snippet that
you can edit. There may be zero or more Object elements in
a Declarations element.
Snippet Element Contains the references, imports, declarations, and code for
the code snippet.
Default Element
Specifies the default value of the literal or object for an IntelliSense Code Snippet.
<Default>
Default value
</Default>
Literal Element Defines the literal fields of the code snippet that you can edit.
Object Element Defines the object fields of the code snippet that you can edit.
A text value is required. This text specifies the default value of the literal or object that fills the fields of the code
snippet that you can edit.
Description Element
Specifies descriptive information about the contents of an IntelliSense Code Snippet.
<Description>
Code Snippet Description
</Description>
Function Element
Specifies a function to execute when the literal or object receives focus in Visual Studio.
NOTE
The Function element is only supported in Visual C# code snippets.
<Function>
FunctionName
</Function>
Literal Element Defines the literal fields of the code snippet that you can edit.
Object Element Defines the object fields of the code snippet that you can edit.
A text value is required. This text specifies a function to execute when the literal or object field receives focus in
Visual Studio.
Specifies general information about the IntelliSense Code Snippet.
<Header>
<Title>... </Title>
<Author>... </Author>
<Description>... </Description>
<HelpUrl>... </HelpUrl>
<SnippetTypes>... </SnippetTypes>
<Keywords>... </Keywords>
<Shortcut>... </Shortcut>
</Header>
Author Element Optional element. The name of the person or company that
authored the code snippet. There may be zero or one
Author elements in a Header element.
Shortcut Element Optional element. Specifies the shortcut text that can be used
to insert the snippet. There may be zero or one Shortcut
elements in a Header element.
Title Element Required element. The friendly name of the code snippet.
There must be exactly one Title element in a Header
element.
HelpUrl Element
Specifies a URL that provides more information about a code snippet.
NOTE
Visual Studio does not use the HelpUrl element. The element is part of the IntelliSense Code Snippet XML schema and any
code snippet containing the element will validate, but the value of the element is never used.
<HelpUrl>
www.microsoft.com
</HelpUrl>
A text value is optional. This text specifies the URL to visit for more information about a code snippet.
ID Element
Specifies a unique identifier for a Literal or Object element. No two literals or objects in the same code snippet
can have the same text value in their ID elements.Literals and objects cannot contain an ID element with a value
of end. The value $end$ is reserved, and is used to mark the location to place the cursor after the code snippet is
inserted.
<ID>
Unique Identifier
</ID>
Literal Element Defines the literal fields of the code snippet that you can edit.
Object Element Defines the object fields of the code snippet that you can edit.
A text value is required. This text specifies the unique identifier for the object or literal.
Import Element
Specifies the imported namespaces used by an IntelliSense Code Snippet.
NOTE
The Import element is only supported for Visual Basic projects.
<Import>
<Namespace>... </Namespace>
</Import>
Namespace Element Required element. Specifies the namespace used by the code
snippet. There must be exactly one Namespace element in an
Import element.
Imports Element
Groups individual Import elements.
NOTE
The Imports element is only supported for Visual Basic projects.
<Imports>
<Import>... </Import>
<Imports>
CHILD ELEMENT DESCRIPTION
Import Element Optional element. Contains the imported namespaces for the
code snippet. There may be zero or more Import elements in
an Imports element.
Snippet Element Contains the references, imports, declarations, and code for
the code snippet.
Keyword Element
Specifies a custom keyword for the code snippet. The code snippet keywords are used by Visual Studio and
represent a standard way for online content providers to add custom keywords for searching or categorization.
<Keyword>
Code Snippet Keyword
</Keyword>
Keywords Element
Groups individual Keyword elements. The code snippet keywords are used by Visual Studio and represent a
standard way for online content providers to add custom keywords for searching or categorization
<Keywords>
<Keyword>... </Keyword>
<Keyword>... </Keyword>
<Keywords>
Keyword Element Optional element. Contains individual keywords for the code
snippet. There may be zero or more Keyword elements in a
Keywords element.
Literal Element
Defines the literals of the code snippet that you can edit. The Literal element is used to identify a replacement
for a piece of code that is entirely contained within the snippet, but will likely be customized after it is inserted into
the code. For example, literal strings, numeric values, and some variable names should be declared as literals.
Literals and objects cannot contain an ID element with a value of selected or end. The value $selected$ represents
text selected in the document that is to be inserted into the snippet when it is invoked. $end$ marks the location
to place the cursor after the code snippet is inserted.
<Literal Editable="true/false">
<ID>... </ID>
<ToolTip>... </ToolTip>
<Default>... </Default>
<Function>... </Function>
</Literal>
ATTRIBUTE DESCRIPTION
Default Element Required element. Specifies the literal's default value when
you insert the code snippet. There must be exactly one
Default element in a Literal element.
ToolTip Element Optional element. Describes the expected value and usage of
the literal. There may be zero or one Tooltip elements in a
Literal element.
Declarations Element Contains the literals and objects of a code snippet that you
can edit.
Namespace Element
Specifies the namespace that must be imported for the code snippet to compile and run. The namespace specified
in the Namespace element is automatically added to an Imports statement at the beginning of the code, if it does
not already exist.
NOTE
The Namespace element is only supported for Visual Basic projects.
<Namespace>
Namespace
</Namespace>
A text value is required. This text specifies a namespace that the code snippet assumes is imported.
Object Element
Defines the objects of the code snippet that you can edit. The Object element is used to identify an item that is
required by the code snippet but is likely to be defined outside of the snippet itself. For example, Windows Forms
controls, ASP.NET controls, object instances, and type instances should be declared as objects. Object declarations
require that a type be specified, which is done with the Type element.
<Object Editable="true/false">
<ID>... </ID>
<Type>... </Type>
<ToolTip>... </ToolTip>
<Default>... </Default>
<Function>... </Function>
</Object>
ATTRIBUTE DESCRIPTION
Default Element Required element. Specifies the literal's default value when
you insert the code snippet. There must be exactly one
Default element in a Literal element.
ToolTip Element Optional element. Describes the expected value and usage of
the literal. There may be zero or one Tooltip elements in a
Literal element.
Type Element Required element. Specifies the type of the object. There must
be exactly one Type element in an Object element.
PARENT ELEMENT DESCRIPTION
Declarations Element Contains the literals and objects of a code snippet that you
can edit.
Reference Element
Specifies information about the assembly references required by the code snippet.
NOTE
The Reference element is only supported for Visual Basic projects.
<Reference>
<Assembly>... </Assembly>
<Url>... </Url>
</Reference>
References Element
Groups individual Reference elements.
NOTE
The References element is only supported for Visual Basic projects.
<References>
<Reference>... </Reference>
</References>
Snippet Element Contains the references, imports, declarations, and code for
the code snippet.
Shortcut Element
Specifies the shortcut text used to insert the snippet. The text value of a Shortcut element can only contain
alphanumeric characters, hyphens ( - ), and underscores ( _ ).
Cau t i on
<Shortcut>
Shortcut Text
</Shortcut>
A text value is optional. This text is used as a shortcut for inserting the code snippet.
Snippet Element
Specifies the references, imports, declarations, and code for the code snippet.
<Snippet>
<References>... </References>
<Imports>... </Imports>
<Declarations>... </Declarations>
<Code>... </Code>
</Snippet>
Code Element Required element. Specifies the code that you want to insert
into a documentation file. There must be exactly one Code
element in a Snippet element.
Declarations Element Optional element. Specifies the literals and objects that make
up the parts of a code snippet that you can edit. There may
be zero or one Declarations elements in a Snippet
element.
CodeSnippet Element Allows you to specify a heading and multiple IntelliSense Code
Snippets, which you can insert into Visual Studio code files.
SnippetType Element
Specifies how Visual Studio inserts the code snippet.
<SnippetType>
SurroundsWith/Expansion
<SnippetType>
SnippetTypes Element
Groups individual SnippetType elements. If the SnippetTypes element is not present, the code snippet can be
inserted anywhere in the code.
<SnippetTypes>
<SnippetType>... </SnippetType>
<SnippetType>... </SnippetType>
<SnippetTypes>
SnippetType Element Optional element. Specifies how Visual Studio inserts the code
snippet into the code. There may be zero or more
SnippetType elements in a SnippetTypes element.
Title Element
Specifies the title for the code snippet. The title stored in the Title element of the code snippet appears in the
Code Snippet Picker and in the code snippet's description in the Code Snippets Manager.
<Title>
Code Snippet Title
<Title>
A text value is required. This text specifies the title of the code snippet.
ToolTip Element
Describes the expected value and usage of a literal or object in a code snippet, which Visual Studio displays in a
ToolTip when it inserts the code snippet into a project. The ToolTip text is displayed when the mouse hovers over
the literal or object after the code snippet has been inserted.
<ToolTip>
ToolTip description
</ToolTip>
Literal Element Defines the literal fields of the code snippet that you can edit.
Object Element Defines the object fields of the code snippet that you can edit.
A text value is required. This text specifies the ToolTip description to be associated with the object or literal in the
code snippet.
Type Element
Specifies the type of the object. The Object element is used to identify an item that is required by the code snippet
but is likely to be defined outside of the snippet itself. For example, Windows Forms controls, ASP.NET controls,
object instances, and type instances should be declared as objects. Object declarations require that a type be
specified, which is done with the Type element.
<Type>
Type
</Type>
Object Element Defines the object fields of the code snippet that you can edit.
A text value is required. This text specifies the type of the object.
Url Element
Specifies a URL that provides more information about the referenced assembly.
NOTE
The Url element is only supported for Visual Basic projects.
<Url>
www.microsoft.com
</Url>
A text value is required. This text specifies a URL with more information about the referenced assembly. This URL is
displayed when the reference cannot be added to the project.
See Also
Code Snippets
Walkthrough: Creating a Code Snippet
Using the Toolbox
10/18/2017 • 2 min to read • Edit Online
You can use the toolbox to add controls and other items to your project. You can drag and drop different controls
onto the surface of the designer you are using, and resize and position the controls.
The toolbox appears in conjunction with designer views, such as the designer view of a XAML file. The toolbox
displays only those controls that can be used in the current designer.
The .NET Framework version that your project targets also affects the set of controls visible in the toolbox. By
default, Visual Studio 2013 projects target the .NET Framework 4.5.1. You can set your project to target a different
version of the .NET Framework by selecting the project node in Solution Explorer, and then browsing to
Properties/Application/Target Framework.
You can examine the objects and members in Visual Studio projects, and the objects and members in .NET
Framework components, COM components, dynamic-link libraries (DLL), and type libraries (TLB).
The following sections of this document describe the different code structure windows.
Class View (Visual Basic, C#, C++)
Call Hierarchy (Visual Basic, C#, C++)
Object Browser
Code Definition Window (C#, C++)
You can also use Solution Explorer to browse the types and members in your projects, search for symbols, view a
method's Call Hierarchy, find symbol references, and more without having to switch between the multiple tool
windows listed previously.
If you have Visual Studio Enterprise you can use code maps to visualize the structure of your code and its
dependencies across the entire solution, and drill down to parts of the code that interest you. For more
information, see Map dependencies across your solutions.
NOTE
The Visual Studio edition and the settings you are using may affect the features in the IDE. They might differ from those
described in this topic.
View Class Diagram (managed code projects only) Becomes available when you select a namespace or type in
Class View. When a namespace is selected, the class diagram
shows all the types in it. When a type is selected, the class
diagram shows only that type.
Show Hidden Types and Members Hidden types and members (not intended for use by clients)
are displayed in light gray text.
Show Other Members Other kinds of members are displayed, including internal (or
Friend in Visual Basic) members.
Filter To Type (managed code only) Displays only the selected type or namespace. You can
remove the filter by choosing the Clear Find (X) button next
to the Find box.
Sort by Member Type Lists types and members in order by type (such that classes
precede interfaces, interfaces precede delegates, and methods
precede properties).
Sort by Member Access Lists types and members in order by access type, such as
public or private.
Group by Member Type Sorts types and members into groups by object type.
Go To Declaration (C++ code only) Displays the declaration of the type or member in the source
code, if available.
View Call Hierarchy Displays the selected method in the Call Hierarchy window.
Add as New Root Adds the selected node as a new root node.
Remove Root Removes the selected root node from the tree view pane.
Find All References Finds in the project all the references to the selected method.
Object Browser
The Object Browser displays descriptions of the code in your projects.
You can filter what you want to view in the Object Browser. By using the drop-down list at the top of the window,
you can choose among the following options:
Any .NET Framework
Silverlight
The active solution
A custom set of components
Custom components can include managed code executables, library assemblies, type libraries, and .ocx files.
It is not possible to add C++ custom components. Custom settings are saved in the Visual Studio user
application directory, %APPDATA%\Roaming\Microsoft\VisualStudio\11.0\ObjBrowEX.dat.
The left pane of the Object Browser shows physical containers such as .NET Framework and COM
components. You can expand the container nodes to display the namespaces they contain, and then expand
the namespaces to display the types they contain. When you select a type, its members (such as properties
and methods) are listed in the right pane. The lower right pane displays detailed information about the
selected item.
You can search for a specific item by using the Search box at the top of the window. Searches are case-
insensitive. Search results are displayed in the left pane. To clear a search, choose the Clear Search (X)
button next to the Search box.
The Object Browser keeps track of the selections you have made, and you can navigate among your
selections by using the Forward and Back buttons on the toolbar.
You can use the Object Browser to add an assembly reference to an open solution by selecting an item
(assembly, namespace, type, or member) and choosing the Add Reference button on the toolbar.
Object Browser Settings
By using the Object Browser Settings button on the toolbar, you can specify one of the following views.
Show Hidden Types and Members Displays hidden types and members (not intended for use by
clients), in light gray text.
Show Other Members Displays other types of members, including internal (or Friend
in Visual Basic) members.
Browse Definition Shows the primary node for the selected item.
Find All References Finds the currently selected object item and displays the
results in a Find Results window.
Filter To Type Displays only the selected type or namespace. You can
remove the filter by choosing the Clear Search button.
Sort by Object Type Lists types and members in order by type (such that classes
precede interfaces, interfaces precede delegates, and methods
precede properties).
Sort by Object Access Lists types and members in order by access type, such as
public or private.
Group by Object Type Sorts types and members into groups by object type.
Go To Declaration (C++ projects only) Displays the declaration of the type or member in the source
code, if available.
View Call Hierarchy Displays the selected method in the Call Hierarchy window.
Create Unit Tests Creates unit tests for the selected element.
Create Private Accessor If a unit test is present in the solution, generates a method
that the test uses to access the code.
Go To Definition Finds the definition (or definitions, for partial classes) and
displays them in a Find Results window.
Find All References Finds the references to the type or member in the solution.
View Call Hierarchy Displays the method in the Call Hierarchy window.
Show Calling Tests If there are unit tests in the project, shows the tests that call
the selected code.
Run Calling Tests If there are unit tests in the project, runs the tests for the
selected code.
Run to Cursor Runs the program in debug mode to the location of the
cursor.
Edit Definition Moves the insertion point to the definition in the code
window.
Choose Encoding Opens the Encoding window so that you can set an encoding
for the file.
See Also
Class View and Object Browser Icons
Class View and Object Browser Icons
10/18/2017 • 1 min to read • Edit Online
Class View and the Object Browser display icons that represent code entities, for example, namespaces, classes,
functions, and variables. The following table illustrates and describes the icons.
Class Operator
Interface Property
Union Event
Enum Constant
Delegate Error
Exception Template
Map Unknown
Type Forwarding
Signal Icons
The following signal icons apply to all the previous icons and indicate their accessibility.
NOTE
If your project is included in a source control database, additional signal icons may be displayed to indicate source-control
status, such as checked in or checked out.
ICON DESCRIPTION
ICON DESCRIPTION
<No Signal Icon> Public. Accessible from anywhere in this component and from
any component that references it.
Sealed.
See Also
Viewing the Structure of Code
Designing and Viewing Classes and Types
10/18/2017 • 1 min to read • Edit Online
Design, visualize, and refactor classes and other types in your code with Class Designer in Visual Studio. Use class
diagrams to create and edit classes in your Visual C# .NET, Visual Basic .NET, or C++ project, understand your
project structure better, or reorganize your code.
Here's more about what you can do with class diagrams:
Design: Edit your project's code by editing the class diagram. Add new elements and delete unwanted ones.
Your changes are reflected in code.
Visualize: Understand your project's structure by viewing the classes in your project on a diagram.
Customize your diagram so that you can focus on the project details that you care about the most. Save
your diagram to use later for demonstration or documentation.
Refactor: Override methods, rename identifiers, refactor parameters, and implement interfaces and abstract
classes.
In This Section
Working with Classes and Other Types (Class Designer)
Working with Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
Viewing Types and Relationships (Class Designer)
Refactoring Classes and Types (Class Designer)
Working with Visual C++ Code (Class Designer)
Additional Information About Class Designer Errors
Related Sections
Writing Code
Map dependencies across your solutions
Working with Classes and Other Types (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
Focus more easily on the classes and types that you care about the most when you create and edit them with Class
Designer in Visual Studio. Use class diagrams to work more visually with your Visual C# .NET, Visual Basic .NET, or
C++ code.
In This Section
Working with Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
Viewing Types and Relationships (Class Designer)
Refactoring Classes and Types (Class Designer)
Working with Visual C++ Code (Class Designer)
Additional Information About Class Designer Errors
Working with Class Diagrams (Class Designer)
10/18/2017 • 2 min to read • Edit Online
Class diagrams help you understand the class structure of projects others have written (or that you wrote a long
time ago). You can use them to customize, share and present project information with others.
The first step in presenting project information is to create a class diagram that displays what you want to show.
For more information, see Viewing Types and Relationships (Class Designer). You can create multiple class
diagrams for a project that can be used to display a distinct view of the project, a chosen subset of the project's
types, or a chosen subset of the members of types.
In addition to defining what each class diagram shows, you can also change the way that information is presented;
for more information, see How to: Customize Class Diagrams (Class Designer).
After you have fine-tuned one or more class diagrams, you can copy them into Microsoft Office documents and
print them, or export them as image files. For more information, see How to: Copy Class Diagram Elements to a
Microsoft Office Document (Class Designer), How to: Print Class Diagrams (Class Designer) and How to: Export
Class Diagrams As Images (Class Designer).
NOTE
Class Designer does not track the location of your source files, so changing your project structure or moving source files in
the project can cause Class Designer to lose track of the type, especially the source type of a typedef, base classes, or
association types. You might get an error, like Class Designer is unable to display this type. If you do, drag the modified
or relocated source code to the class diagram again to redisplay it.
In This Section
How to: Add Class Diagrams to Projects (Class Designer)
Describes how to add class diagrams to projects.
How to: Customize Class Diagrams (Class Designer)
Provides information about how to customize class diagrams.
How to: Copy Class Diagram Elements to a Microsoft Office Document (Class Designer)
Explains how to copy from a class diagram into an Office document.
How to: Export Class Diagrams As Images (Class Designer)
Describes how to export class diagrams as images.
How to: Print Class Diagrams (Class Designer)
Explains how to print class diagrams.
How to: Add Comments to Class Diagrams (Class Designer)
Describes how to add comments to a class diagram.
To delete a type shape and its underlying code
Describes how to remove shapes from class diagrams.
See Also
Viewing Types and Relationships (Class Designer)
How to: Customize Class Diagrams (Class Designer)
How to: Remove Type Shapes from Class Diagrams (Class Designer)
How to: Add Class Diagrams to Projects (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
To design, edit, and refactor classes and other types, add a class diagram to your Visual C# .NET, Visual Basic .NET,
or C++ project. To visualize different parts of the code in a project, add multiple class diagrams to the project.
You can't create class diagrams from projects that share code across multiple apps. To create UML class diagrams,
see Create UML modeling projects and diagrams.
To add a blank class diagram to a project
1. In Solution Explorer, right-click the project name. Then choose Add New Item or Add, New Item.
2. From the template list, choose the Class Diagram. For Visual C++ projects, look under Templates, and
then under Utility to find this template.
The class diagram opens in Class Designer and appears as a file that has a .cd extension in Solution Explorer
in the project hierarchy. Use the Class Designer toolbox to drag shapes and lines to the diagram.
3. To add multiple class diagrams, repeat the steps in this procedure.
To add a class diagram based on existing types
1. In Solution Explorer, open the class file context menu, then choose View Class Diagram.
-or-
In Class View, open the namespace or type context menu, then choose View Class Diagram.
To display the contents of a complete project in a class diagram
1. In Solution Explorer or Class View, right-click the project and choose View, then choose View Class
Diagram.
An auto-populated Class Diagram is created.
See Also
How to: Create Types by using Class Designer
How to: View Existing Types (Class Designer)
Designing Classes and Types (Class Designer)
Viewing Types and Relationships (Class Designer)
Working with Class Diagrams (Class Designer)
How to: Customize Class Diagrams (Class Designer)
10/18/2017 • 3 min to read • Edit Online
You can change the way that class diagrams display information. You can customize the whole diagram or the
individual types on the design surface.
For example, you can adjust the zoom level of an entire class diagram, change how individual type members are
grouped and sorted, hide or show relationships, and move individual or sets of types anywhere on the diagram.
NOTE
Customizing the way that shapes appear on the diagram doesn't change the underlying code for the types represented on
the diagram.
The sections that contain type members, such as the Properties section in a class, are called compartments. You
can hide or show individual compartments and type members.
In this topic
Zoom in and out of the class diagram
Customize grouping and sorting of type members
Hide compartments on a type
Hide individual members on a type
Show hidden compartments and members on a type
Hide relationships
Show hidden relationships
Remove a shape from a class diagram
Delete a type shape and its underlying code
NOTE
Changing the zoom level does not affect the scale of your class diagram printout.
Hide relationships
1. Open and select a class diagram file in Class Designer.
2. Right-click the association or inheritance line that you want to hide.
3. Click Hide for association lines, and click Hide Inheritance Line for inheritance lines.
4. Click Show All Members.
All hidden compartments and members appear in the type container.
See Also
Working with Class Diagrams (Class Designer)
How to: Change Between Member Notation and Association Notation (Class Designer)
How to: View Existing Types (Class Designer)
Viewing Types and Relationships (Class Designer)
How to: Copy Class Diagram Elements to a Microsoft
Office Document (Class Designer)
10/18/2017 • 1 min to read • Edit Online
You can copy shapes from a .NET class diagram (.cd file) to other documents. You'll either get a copy of the shape
or its underlying code based on the kind of document where you paste it. To copy shapes from UML class
diagrams in a modeling project, see Export diagrams as images.
To copy a single element
Right-click the shape and choose Copy Image.
To copy several elements
1. Select the shapes on the diagram that you want to copy.
2. Right-click your selection and choose Copy Image.
To copy all the elements in a class diagram
1. Right-click the diagram surface and choose Select All. (Keyboard: Ctrl + A)
2. On the Edit menu, select Copy Image.
You can also choose Copy instead of Copy Image. Copy copies the image as a regular bitmap. Copy
Image copies the image as a vector-based image, which is better for most Office applications.
See Also
How to: Print Class Diagrams (Class Designer)
How to: Export Class Diagrams As Images (Class Designer)
How to: Export Class Diagrams As Images (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
To export a class diagram that you created from code in a project, save the diagram as an image. If you want to
export UML class diagrams instead, see Export diagrams as images.
1. Open your class diagram (.cd) file.
2. From the Class Diagram menu or the diagram surface shortcut menu, choose Export Diagram as Image.
3. Select a diagram.
4. Select the format that you want.
5. Choose Export to finish exporting.
To automatically update exported images that are linked from other documents, export the diagram again
in Visual Studio.
See Also
How to: Print Class Diagrams (Class Designer)
Working with Class Diagrams (Class Designer)
How to: Print Class Diagrams (Class Designer)
10/18/2017 • 1 min to read • Edit Online
You can print a class diagram using the print feature of Visual Studio.
To print a class diagram
1. Display the class diagram. (If necessary, select the class diagram tab to display it.)
2. Click Print on the File menu.
The entire class diagram will print. Note that you may need to adjust the settings in the Page Setup Dialog
box in order to print at an appropriate size.
See Also
How to: Copy Class Diagram Elements to a Microsoft Office Document (Class Designer)
How to: Export Class Diagrams As Images (Class Designer)
How to: Add Comments to Class Diagrams (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
You can use comment shapes to annotate class diagrams. A comment shape has one property, Text, into which you
can type text. Comment shapes exist only on the diagram surface and not in code.
A comment resides on the class diagramview in Class Designer; if you open a second class diagram onto the same
project, comments you created in the first view are not visible. If you delete a diagram, all the comments it
contained are also deleted.
You can resize a comment shape but you cannot change other aspects of its appearance, such as its background
color, font, or font size.
To add a comment
1. Drag a comment from the Class Designer Toolbox onto the class diagram.
2. Click in the new comment shape on the diagram and type the text you want.
See Also
Working with Class Diagrams (Class Designer)
Working with Class Diagrams (Class Designer)
How to: Customize Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
10/18/2017 • 1 min to read • Edit Online
Using Class Designer, you can not only visualize classes and types, but design them as well. The following topics
describe how to do this.
NOTE
When working with the Class Designer, you should inspect the code it emits before executing it in order to verify that the
code is appropriate for your security context.
In This Section
How to: Create Types by using Class Designer
Describes how to use the Class Diagram to create a type.
How to: Create Inheritance Between Types (Class Designer)
Explains how to define an inheritance relationship between types.
How to: Create Associations Between Types (Class Designer)
Describes how to define associations in the class diagram.
How to: Visualize a Collection Association (Class Designer)
Explains how to define a collection association in the Class Designer.
Creating and Configuring Type Members (Class Designer)
Provides information and links to topics about creating and configuring type members with the Class Designer.
Related Sections
Viewing Types and Relationships (Class Designer)
Refactoring Classes and Types (Class Designer)
See Also
Working with Class Diagrams (Class Designer)
How to: Create Types by using Class Designer
10/18/2017 • 2 min to read • Edit Online
To design new types for Visual C# .NET and Visual Basic .NET projects, create them on a class diagram. To see
existing types, see How to: View Existing Types (Class Designer).
Create a new type
Apply a custom attribute to a type
Apply a custom attribute to a type member
For Add
Classes, abstract classes, structures or structs Methods, properties, fields, events, constructors (method),
destructors (method), and constants that define the type
See Also
How to: Create Inheritance Between Types (Class Designer)
How to: Create Associations Between Types (Class Designer)
Creating and Configuring Type Members (Class Designer)
Working with Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
How to: Create Inheritance Between Types (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
To create an inheritance relationship between two types on a class diagram using Class Designer, connect the base
type with its derived type or types. You can have an inheritance relationship between two classes, between a class
and an interface, or between two interfaces.
To create an inheritance between types
1. From your project in Solution Explorer, open a class diagram (.cd) file.
If you don't have a class diagram, create it. See How to: Add Class Diagrams to Projects (Class Designer).
2. In the Toolbox, under Class Designer, click Inheritance.
3. On the class diagram, draw an inheritance line between the types that you want, starting from:
A derived class to the base class
An implementing class to the implemented interface
An extending interface to the extended interface
4. Optionally, when you have a derived type from a generic type, click the inheritance line. In the Properties
window, set the Type Arguments property to match the type that you want for the generic type.
NOTE
If a parent abstract class contains at least one abstract member, then all abstract members are implemented as non-
abstract inheriting classes.
Although you can visualize existing generic types, you can't create new generic types. You also can't change the type
parameters for existing generic types.
See Also
Inheritance
Inheritance Basics
How to: View Inheritance Between Types (Class Designer)
Visual C++ Classes in Class Designer
How to: Create Associations Between Types (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
Association lines in Class Designer show how classes in a diagram are related. An Association line represents a
class that is the type of a property or field of another class in your project. Association lines are generally used to
illustrate the most important relationships between classes in your project.
While you could display all fields and properties as associations, it makes more sense to show only important
members as associations, depending on what you intend to emphasize in the diagram. (You can show less
important members as regular members or hide them altogether.)
NOTE
Class Designer supports only unidirectional associations.
See Also
How to: Change Between Member Notation and Association Notation (Class Designer)
How to: Visualize a Collection Association (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
Properties and fields that are collections of other types can be displayed on the class diagram as a collection
association. Unlike a regular association, which displays a field or property as a line linking the owning class to the
field's type, a collection association is displayed as a line linking the owning class to the collected type.
To create a collection association
1. In code, create a property or field whose type is itself a strongly-typed collection.
2. In the class diagram, expand the class so that properties and fields are shown.
3. In the class, right-click the field or property and choose Show as Collection Association.
The property or field is shown as an association line linking to the collected type.
See Also
How to: Create Associations Between Types (Class Designer)
Designing Classes and Types (Class Designer)
Viewing Types and Relationships (Class Designer)
Creating and Configuring Type Members (Class
Designer)
10/18/2017 • 13 min to read • Edit Online
You can add these members to types on a class diagram and configure those members in the Class Details
window:
Class method, property (for C# and Visual Basic), field, event (for C#
and Visual Basic), constructor (method), destructor (method),
constant
Enum member
Abstract Class method, property (for C# and Visual Basic), field, event (for C#
and Visual Basic), constructor (method), destructor (method),
constant
Structure (Struct in C#) method, property (for C# and Visual Basic) field, event (for C#
and Visual Basic), constructor (method), constant
Delegate Parameter
NOTE
Make property declaration more concise when a property's get and set accessors don't need additional logic by using auto-
implemented properties (C# only). To show the full signature, from the Class Diagram menu, choose Change Members
Format, Display Full Signature. For more information about auto-implemented properties, see Auto-Implemented
Properties.
Common Tasks
TASK SUPPORTING CONTENT
Get started: Before you create and configure type members, - Opening the Class Details Window
you must open the Class Details window. - Class Details Usage Notes
- Display of Read-Only Information
- Keyboard and Mouse Shortcuts in the Class Diagram and
Class Details Window (Class Designer)
Create and modify type members: You can create new - Creating Members
members, modify members, and add parameters to a method - Modifying Type Members
by using the Class Details window. - Adding Parameters to Methods
Opening the Class Details Window
By default, the Class Details Window appears automatically when you open a new class diagram (see How to: Add
Class Diagrams to Projects (Class Designer)). You can also open the Class Details window explicitly, in the following
ways.
To open the Class Details window
1. Right-click on any class in the diagram to display a context menu.
2. In the context menu, click Class Details Window.
or -
Point to Other Windows on the View menu and then click Class Details.
Creating Members
You can create a member using any of the following tools:
Class Designer
Class Details window toolbar
Class Details window
NOTE
You can also create constructors and destructors using the procedures in this section. Please bear in mind that constructors
and destructors are special kinds of methods, and as such, they appear in the Methods compartment in class diagram
shapes and in the Methods section of the Class Details window grid.
NOTE
The only entity you can add to a delegate is parameter. Note that the procedure entitled 'To Create a member using the
Class Details Window toolbar' is not valid for this action.
NOTE
If you want to modify only the name of a member, you can do so by using in-place editing.
NOTE
To add a parameter to a delegate, see Creating Members.
NOTE
Although a destructor is a method, it cannot have parameters.
NOTE
Optional parameters must be the last parameters in the parameter list.
Related Topics
TITLE DESCRIPTION
Viewing Types and Relationships (Class Designer) You can view your existing types, members, and relationships
in a class diagram.
Refactoring Classes and Types (Class Designer) By using refactoring, you can easily rename type and type
members. You can also move members between classes, split
a class into partial classes, and implement interfaces.
Keyboard and Mouse Shortcuts in the Class Diagram
and Class Details Window (Class Designer)
10/18/2017 • 5 min to read • Edit Online
You can use the keyboard in addition to the mouse to perform navigational actions in Class Designer and in the
Class Details window.
In this topic
Using the Mouse in Class Designer
Using the Mouse in the Class Details Window
Using the Keyboard in Class Designer
Using the Keyboard in the Class Details Window
ALT+SHIFT+L Inside type shapes + on type shapes. Navigates to the lollipop of currently
selected shape if it is present.
ALT+SHIFT+B Inside type shapes + on type shapes. If base type list is shown on the type
shape and has more than one item, this
toggles expansion state of the list
(collapse/expand).
Key Result
) (close parenthesis)
Tab Moves the cursor to the next field, first moving left to right
and then top to bottom. If the cursor is moving from a field in
which you have typed text, Class Details Window processes
that text and stores it if it does not produce an error.
<space> Moves the cursor to the next field, first moving left to right
and then top to bottom. If the cursor is on an empty field
such as <add parameter>, it moves to the first field of the
next row. Note that <space> typed immediately after a
comma is ignored.
ESC (Escape) If you have begun to type text in a field, pressing ESC acts as
an undo key, reverting the field's contents to its previous
value. If the Class Details Window has general focus, but no
specific cell has focus, pressing ESC moves focus away from
the Class Details Window.
Up arrow and down arrow These keys move the cursor from row to row vertically in the
Class Details Window grid.
Left arrow If the cursor is in the Name column, pressing the left arrow
collapses the current node in the hierarchy (if it is open).
Right arrow If the cursor is in the Name column, pressing the right arrow
expands the current node in the hierarchy (if it is collapsed).
See Also
Creating and Configuring Type Members (Class Designer)
Viewing Types and Relationships (Class Designer)
10/18/2017 • 1 min to read • Edit Online
Class Designer uses class diagrams to show you the details of types, for example, their constituent members, and
the relationships that they share. The visualization of these entities is actually a dynamic view into the code. This
means that you can edit types on the designer and then see your edits reflected in the source code of the entity.
Similarly, the class diagram is kept synchronized with changes you make to entities in code.
NOTE
If your project contains a class diagram and if your project references a type that is located in another project, the class
diagram does not show the referenced type until you build the project for that type. Likewise, the diagram does not
display changes to the code of the external entity until you rebuild the project for that entity. For information about type
in referenced assemblies and read-only files, see Display of Read-Only Information (Class Designer).
In This Section
How to: View Existing Types (Class Designer)
Describes how Class Designer can be used to visualize pre-existing code.
How to: View Inheritance Between Types (Class Designer)
Describes how to view the inheritance relationships between types.
How to: Change Between Member Notation and Association Notation (Class Designer)
Describes how to switch between member notation and association notation.
Related Sections
Designing Classes and Types (Class Designer)
Refactoring Classes and Types (Class Designer)
How to: Customize Class Diagrams (Class Designer)
Working with Class Diagrams (Class Designer)
How to: View Existing Types (Class Designer)
10/18/2017 • 2 min to read • Edit Online
To see an existing type and its members, add its shape to a class diagram.
You can see local and referenced types. A local type exists in the currently open project and is read/write. A
referenced type exists in another project or in a referenced assembly and is read-only.
To design new types on class diagrams, see How to: Create Types by using Class Designer.
To see types in a project on a class diagram
1. From a project in Solution Explorer, open an existing class diagram (.cd) file. Or if no class diagram exists,
add a new class diagram to the project. See How to: Add Class Diagrams to Projects (Class Designer).
2. From the project in Solution Explorer, drag a source code file to the class diagram.
WARNING
If your solution has a project that shares code across multiple apps, you can drag files or code to a class diagram
only from these sources:
The app project that contains the diagram
A shared project that was imported by the app project
A referenced project
An assembly
Shapes representing the types defined in the source code file appear on the diagram at the position where
you dragged the file.
You can also view types in the project by dragging one or more types from the project node in Class View
to the class diagram.
TIP
If Class View is not open, open Class View from the View menu. For more information about Class View, see Viewing Classes
and Their Members.
To display types at default locations on the diagram, select one or more types in Class View, right-click the selected
types, and choose View Class Diagram.
NOTE
If a closed class diagram containing the type already exists in the project, the class diagram opens to display the type shape.
However, if no class diagram containing the type exists in the project, Class Designer creates a new class diagram in the
project and opens it to display the type.
When you first display a type on the diagram, its shape appears collapsed by default. You can expand the shape to
view its contents.
To display the contents of a project in a class diagram
1. In Solution Explorer or Class View, right-click the project and choose View, then choose View Class
Diagram.
An auto-populated Class Diagram is created.
See Also
How to: View Inheritance Between Types (Class Designer)
How to: Customize Class Diagrams (Class Designer)
Viewing Types and Relationships (Class Designer)
How to: View Inheritance Between Types (Class
Designer)
10/18/2017 • 1 min to read • Edit Online
You can find the inheritance relationship, if it exists, between a base type and its derived types on a class diagram
in Class Designer. To create an inheritance relationship, if none exist, between two types, see How to: Create
Inheritance Between Types (Class Designer).
To find the base type
1. On the class diagram, click the type for which you want to see the base class or interface.
2. On the Class Diagram menu, choose Show Base Class or Show Base Interfaces.
The type's base class or interface appears selected on the diagram. Any hidden inheritance lines now appear
between the two shapes.
You can also right-click the type whose base type you want to display, and choose Show Base Class or
Show Base Interfaces.
To find the derived types
1. On the class diagram, click the type for which you want to see the derived classes or interfaces.
2. On the Class Diagram menu, choose Show Derived Classes or Show Derived Interfaces.
The type's derived classes or interfaces appear on the diagram. Any hidden inheritance lines now appear
between the shapes.
You can also right-click the type for which you want to see its derived types, and choose Show Derived
Classes or Show Derived Interfaces.
See Also
How to: Create Associations Between Types (Class Designer)
Viewing Types and Relationships (Class Designer)
How to: Change Between Member Notation and
Association Notation (Class Designer)
10/18/2017 • 1 min to read • Edit Online
In Class Designer, you can change the way the class diagram represents an association relationship between two
types from member notation to association notation and vice versa. Members displayed as association lines often
provide a useful visualization of how types are related.
NOTE
Association relationships can be represented as a member property or field. To change member notation to association
notation, one type must have a member of another type. To change association notation to member notation, the two types
must be connected by an association line. For more information, see How to: Create Associations Between Types (Class
Designer). If your project contains multiple class diagrams, changes that you make to the way a diagram displays association
relationships affect only that diagram. To change the way another diagram displays association relationships, open or display
that diagram and perform these steps.
TIP
If no properties or fields are visible in the type shape, the compartments in the shape might be collapsed. To expand
the type shape, double-click the compartment name or right-click the type shape, and choose Expand.
The member disappears from the compartment in the type shape and an association line appears to
connect the two types. The association line is labeled with the name of the property or field.
To change association notation to member notation
On the class diagram, right-click the association line, and choose Show as Property or Show as Field as
appropriate.
The association line disappears, and the property displays in the appropriate compartment within its type
shape on the diagram.
See Also
How to: Create Inheritance Between Types (Class Designer)
How to: View Inheritance Between Types (Class Designer)
Viewing Types and Relationships (Class Designer)
How to: Visualize a Collection Association (Class Designer)
Refactoring Classes and Types (Class Designer)
10/18/2017 • 3 min to read • Edit Online
When you refactor code, you make it easier to understand, maintain, and more efficient by changing its internal
structure and how its objects are designed, not its external behavior. Use Class Designer and the Class Details
window to reduce the work that you have to do and the chance of introducing bugs when you refactor Visual C#
.NET, Visual Basic .NET, or C++ code in your Visual Studio project.
NOTE
The files of a project might be read-only because the project is under source-code control and is not checked out; it is a
referenced project; or its files are marked as read-only on disk. When you work in a project in one of these states, you will be
presented with various ways to save your work depending on the project's state. This applies to refactoring code and also to
code that you change in another way, such as directly editing it. For more information, see Display of Read-Only
Information (Class Designer).
Common Tasks
TASK SUPPORTING CONTENT
Refactoring classes: You can use refactoring operations to - How to: Split a Class into Partial Classes (Class Designer)
split a class into partial classes or to implement an abstract
base class.
Working with interfaces: In Class Designer, you can - How to: Implement an Interface (Class Designer)
implement an interface on the class diagram by connecting it
to a class that provides code for the interface methods.
Refactoring types, type members, and parameters: By - Renaming Types and Type Members
using Class Designer, you can rename types, override type - Moving Type Members from One Type to Another
members, or move them from one type to another. You can - How to: Create a Nullable Type (Class Designer)
also create nullable types.
1. On the class diagram, select the type or member and click on the name.
The name of the member becomes editable.
2. Type the new name for the type or type member
To r e n a m e a n a m e i n t h e C l a ss D e t a i l s W i n d o w
1. To display the Class Details window, right-click the type or type member and then click Class Details.
The Class Details window appears.
2. In the Name column, change the name of the type member
3. To move focus away from the cell, press the ENTER key or click away from the cell.
NOTE
In the Class Details window, you can change the name of a member but not a type.
To r e n a m e a n a m e i n t h e P r o p e r t i e s w i n d o w
1. On the class diagram or the Class Details window, right-click the type or member and then click
Properties.
The Properties window appears and displays properties for the type or type member.
2. In the Name property, change the name of the type or type member.
The new name propagates to all windows and code locations in the current project where the old name
appeared.
Moving Type Members from One Type to Another
Using Class Designer, you can move a type member from one type to another type, if both are visible in the
current class diagram.
To m o v e a t y p e m e m b e r fr o m o n e t y p e t o a n o t h e r
1. In a type that is visible on the design surface, right-click the member you want to move to another type, and
then click Cut.
2. Right-click the destination type and then click Paste.
The property is removed from the source type and appears in the destination type.
Related Topics
TITLE DESCRIPTION
In Class Designer, you can implement an interface on the class diagram by connecting it to a class that provides
code for the interface methods. Class Designer generates an interface implementation and displays the relationship
between the interface and the class as an inheritance relationship. You can implement an interface by drawing an
inheritance line between the interface and the class or by dragging the interface from Class View.
TIP
You can create interfaces the same way you create other types. If the interface exists but does not appear on the class
diagram, then first display it. For more information, see How to: Create Types by using Class Designer and How to: View
Existing Types (Class Designer).
TIP
If Class View is not open, open Class View from the View menu. For more information about Class View, see Viewing
Classes and Their Members.
See Also
How to: Create Types by using Class Designer
How to: View Existing Types (Class Designer)
How to: Create Inheritance Between Types (Class Designer)
Refactoring Classes and Types (Class Designer)
How to: Split a Class into Partial Classes (Class
Designer)
10/18/2017 • 2 min to read • Edit Online
You can divide the declaration of a class or structure among several declarations by using the Partial keyword in
Visual Basic or the partial keyword in Visual C#. You can use as many partial declarations as you want, in as
many different source files as you want, or in one source file. However, all the declarations must be in the same
assembly and the same namespace.
Partial classes are useful in several situations. For example, when you are working on large projects, separating a
class into more than one file enables more than one programmer to work on it at the same time. When you are
working with code that Visual Studio generates, you can change the class without having to re-create the source
file. (Examples of code that Visual Studio generates include Windows Forms and Web Service wrapper code.) You
can thus create code that uses auto-generated classes without having to modify the file that Visual Studio creates.
There are two kinds of partial methods. In Visual C#, they are called declaring and implementing; in Visual Basic,
they are called declaration and implementation.
Class Designer supports partial classes and methods. The type shape in the class diagram refers to a single
declaration location for the partial class. If the partial class is defined in multiple files, you can specify which
declaration location Class Designer will use by setting the New Member Location property in the Properties
window. That is, when you double-click a class shape, Class Designer goes to the source file that contains the class
declaration identified by the New Member Location property. When you double-click a partial method in a class
shape, Class Designer goes to the partial method declaration. Also, in the Properties window, the File Name
property refers to the declaration location. For partial classes, File Name lists all of the files that contain declaration
and implementation code for that class. However, for partial methods, File Name lists only the file that contains the
partial method declaration.
The following examples split the definition of class Employee into two declarations, each of which defines a
different procedure. The two partial definitions in the examples could be in one source file or in two different source
files.
NOTE
Visual Basic uses partial-class definitions to separate Visual Studio—generated code from user-authored code. The code is
separated into discrete source files. For example, the Windows Form Designer defines partial classes for controls such as
Form . You should not modify the generated code in these controls.
For more information about partial types in Visual Basic, see Partial.
Example
To split a class definition in Visual Basic, use the Partial keyword, as shown in the following example.
' First part of class definition.
Partial Public Class Employee
Public Sub CalculateWorkHours()
End Sub
End Class
Example
To split a class definition in Visual C#, use the partial keyword, as shown in the following example.
See Also
Partial Classes and Methods
partial (Type)
partial (Method) (C# Reference)
Partial
How to: Create a Nullable Type (Class Designer)
10/18/2017 • 3 min to read • Edit Online
Certain value types do not always have (or need) a defined value. This is common practice in databases, where
some fields might not be assigned any value. For example, you might assign a null value to a database field to
signify that it has not yet been assigned a value.
A nullable type is a value type that you extend so that it takes the typical range of values for that type and also a
null value. For example, a nullable of Int32 , also denoted as Nullable<Int32>, can be assigned any value from -
2147483648 to 2147483647, or it can be assigned a null value. A Nullable<bool> can be assigned the values
True , False , or null (no value at all).
Nullable types are instances of the Nullable<T> structure. Each instance of a nullable type has two public read-only
properties, HasValue and Value :
HasValue is of type bool and indicates whether the variable contains a defined value. True means that the
variable contains a non-null value. You can test for a defined value by using a statement such as
if (x.HasValue) or if (y != null) .
Value is of the same type as the underlying type. If HasValue is True , Value contains a meaningful value.
If HasValue is False , accessing Value will throw an invalid operation exception.
By default, when you declare a variable as a nullable type, it has no defined value ( HasValue is False ), other
than the default value of its underlying value type.
Class Designer displays a nullable type just as it displays its underlying type.
For more information about nullable types in Visual C#, see Nullable Types. For more information about
nullable types in Visual Basic, see Nullable Value Types.
NOTE
Your computer might show different names or locations for some of the Visual Studio user interface elements in the
following instructions. The Visual Studio edition that you have and the settings that you use determine these
elements. For more information, see Personalizing the IDE.
See Also
Nullable<T>
Nullable Types
Using Nullable Types
How to: Identify a Nullable Type
Nullable Value Types
Working with Visual C++ Code (Class Designer)
10/18/2017 • 5 min to read • Edit Online
Class Designer displays a visual design surface called a class diagram that provides a visual representation of the
code elements in your project. You can use class diagrams to design and visualize classes and other types in a
project.
Class Designer supports the following C++ code elements:
Class (resembles a managed class shape, except that it can have multiple inheritance relationships)
Anonymous class (displays Class View's generated name for the anonymous type)
Template class
Struct
Enum
Macro (displays the post-processed view of the macro)
Typedef
NOTE
This is not the same as the UML class diagram, which you can create in a Modeling Project. For more information, see UML
Class Diagrams: Reference.
For Visual C++ projects, the Class Designer reads only the definition of the type. For example, assume that
you define a type in a header (.h) file and define its members in an implementation (.cpp) file. If you invoke
"View Class Diagram" on the implementation (.cpp) file, Class Designer displays nothing. As another
example, if you invoke "View Class Diagram" on a .cpp file that uses an #include statement to include other
files but does not contain any actual class definitions, Class Designer again displays nothing.
IDL (.idl) files, which define COM interfaces and type libraries, do not display in diagrams unless they are
compiled to native C++ code.
Class Designer does not support global functions and variables.
Class Designer does not support unions. This is a special type of class in which the memory allocated is only
the amount necessary for the union's largest data member.
Class Designer does not display basic data types such as int and char .
Class Designer does not display types that are defined outside the current project if the project does not
have correct references to those types.
Class Designer can display nested types but not the relationships between a nested type and other types.
Class Designer cannot display types that are void or that derive from a void type.
See Also
Designing and Viewing Classes and Types
Working with Classes and Other Types (Class Designer)
Working with Class Diagrams (Class Designer)
Designing Classes and Types (Class Designer)
Additional Information About Class Designer Errors
Visual C++ Classes in Class Designer
Visual C++ Structures in Class Designer
Visual C++ Enumerations in Class Designer
Visual C++ Typedefs in Class Designer
Visual C++ Classes in Class Designer
10/18/2017 • 5 min to read • Edit Online
Class Designer supports C++ classes and visualizes native C++ classes in the same way as Visual Basic and Visual
C# class shapes, except that C++ classes can have multiple inheritance relationships. You can expand the class
shape to show more fields and methods in the class or collapse it to conserve space.
NOTE
Class Designer does not support unions (a special type of class in which the memory allocated is only the amount necessary
for the union's largest data member).
Simple Inheritance
When you drag more than one class onto a class diagram, and the classes have a class inheritance relationship, an
arrow connects them. The arrow points in the direction of the base class. For example, when the following classes
are displayed in a class diagram, an arrow connects them, pointing from B to A:
class A {};
class B : A {};
You can also drag only class B to the class diagram, right-click the class shape for B, and then click Show Base
Classes. This displays its base class: A.
Multiple Inheritance
Class Designer supports the visualization of multiple-class inheritance relationships. Multiple inheritance is used
when a derived class has attributes of more than one base class. Following is an example of multiple inheritance:
When you drag more than one class onto the class diagram, and the classes have a multiple-class inheritance
relationship, an arrow connects them. The arrow points in the direction of the base classes.
Right-clicking a class shape and then clicking Show Base Classes displays the base classes for the selected class.
NOTE
The Show Derived Classes command is not supported for C++ code. You can display derived classes by going to Class
View, expanding the type node, expanding the Derived Types subfolder, and then dragging those types onto the class
diagram.
For more information about multiple-class inheritance, see Multiple Inheritance and Multiple Base Classes.
Abstract Classes
Class Designer supports abstract classes (also named "abstract base classes"). These are classes that you never
instantiate, but from which you can derive other classes. Using an example from "Multiple Inheritance" earlier in
this document, you might instantiate the Bird class as individual objects as follows:
int main()
{
Bird sparrow;
Bird crow;
Bird eagle;
}
However, you might not intend to instantiate the Swimmer class as individual objects. You might intend only to
derive other types of animal classes from it, for example, Penguin , Whale , and Fish . In that case, you would
declare the Swimmer class as an abstract base class.
To declare a class as abstract, you can use the abstract keyword. Members marked as abstract, or included in an
abstract class, are virtual and must be implemented by classes that derive from the abstract class.
You can also declare a class as abstract by including at least one pure virtual function:
class Swimmer
{
virtual void swim() = 0;
void dive();
};
When you display these declarations in a Class Diagram, the class name Swimmer and its pure virtual function
swim are in displayed in italic in an abstract class shape, together with the notation Abstract Class. Notice that the
abstract class type shape is the same as that of a regular class, except that its border is a dotted line.
A class derived from an abstract base class must override each pure virtual function in the base class, or the
derived class cannot be instantiated. So, for example, if you derive a Fish class from the Swimmer class, Fish
must override the swim method:
int main()
{
Fish guppy;
}
When you display this code in a Class Diagram, Class Designer draws an inheritance line from Fish to Swimmer .
Anonymous Classes
Class Designer supports anonymous classes. Anonymous class types are classes declared without an identifier.
They cannot have a constructor or destructor, cannot be passed as arguments to functions, and cannot be returned
as return values from functions. You can use an anonymous class to replace a class name with a typedef name, as
in the following example:
typedef struct
{
unsigned x;
unsigned y;
} POINT;
Structures can also be anonymous. Class Designer displays anonymous classes and structures the same as it
displays the respective type. Although you can declare and display anonymous classes and structures, Class
Designer will not use the tag name that you specify. It will use the name that Class View generates. The class or
structure appears in Class View and Class Designer as an element called __unnamed.
For more information about anonymous classes, see Anonymous Class Types.
Template Classes
Class Designer supports the visualization of template classes. Nested declarations are supported. The following
table shows some typical declarations.
{}; C
{};
(points to Class A)
The following table shows some examples of partial specialization template functions.
class A A
};
template<> template<>
C<T>
Template Class
template<> ->B
C<T>
class A : C<int>::B {};
Template Class
The following table shows some examples of canonical specialized class connection.
template<> ->C<int>
Template Class
Class
->C<float>
CODE ELEMENT CLASS DESIGNER VIEW
class B { B
};
See Also
Working with Visual C++ Code (Class Designer)
Classes and Structs
Anonymous Class Types
Multiple Inheritance
Multiple Base Classes
Templates
Visual C++ Structures in Class Designer
10/18/2017 • 1 min to read • Edit Online
Class Designer supports C++ structures, which are declared with the keyword struct . Following is an example:
struct MyStructure
{
char a;
int i;
long j;
};
For more information about using the struct type, see struct.
A C++ structure shape in a class diagram looks and works like a class shape, except that the label reads Struct and
it has square corners instead of rounded corners.
Struct
See Also
Working with Visual C++ Code (Class Designer)
Classes and Structs
struct
Visual C++ Enumerations in Class Designer
10/18/2017 • 1 min to read • Edit Online
Class Designer supports C++ enum and scoped enum class types. Following is an example:
enum CardSuit {
Diamonds = 1,
Hearts = 2,
Clubs = 3,
Spades = 4
};
// or...
enum class CardSuit {
Diamonds = 1,
Hearts = 2,
Clubs = 3,
Spades = 4
};
A C++ enumeration shape in a class diagram looks and works like a structure shape, except that the label reads
Enum or Enum class, it is pink instead of blue, and it has a colored border on the left and top margins. Both
enumeration shapes and structure shapes have square corners.
For more information about using the enum type, see Enumerations.
See Also
Working with Visual C++ Code (Class Designer)
Enumerations
Visual C++ Typedefs in Class Designer
10/18/2017 • 2 min to read • Edit Online
Typedef statements create one or more layers of indirection between a name and its underlying type. The Class
Designer supports C++ typedef types, which are declared with the keyword typedef , for example:
Although you can declare a typedef without a name, Class Designer will not use the tag name that you specify; it
will use the name that Class View generates. For example, the following declaration is valid, but it appears in Class
View and Class Designer as an object named __unnamed:
For more information about using the typedef type, see typedef Specifier.
A C++ typedef shape has the shape of the type specified in the typedef. For example, if the source declares
typedef class , the shape has rounded corners and the label Class. For typedef struct , the shape has square
corners and the label Struct.
Classes and structures can have nested typedefs declared within them; therefore, class and structure shapes can
show nested typedef declarations as nested shapes.
Typedef shapes support the Show as Association and Show as Collection Association commands on the
context menu.
The following are some examples of typdef types that the Class Designer supports:
typedef type name
name : type
typedef
Draws an association line connecting to type name, if possible.
typedef void (*func)(int)
typedef
Typedef for function pointers. No association line is drawn.
Class Designer does not display a typedef if its source type is a function pointer.
MyInt: int
typedef
A
Class
Draws an association line pointing from the source type shape to the target type shape.
Class B {};
typedef B MyB;
Class
MyB : B
typedef
Right-clicking a typedef shape and clicking Show As Association displays the typedef or class and an Alias of line
joining the two shapes (similar to an association line).
typedef B MyB;
typedef MyB A;
MyBar : Bar
typedef
Same as above.
Class B {};
typedef B MyB;
class A {
MyB B;
};
Class
MyB : B
typedef
A
Class
MyB is a nested typedef shape.
#include <vector>
...
...
vector<T> Class
MyIntVect : vector<int>
typedef
class B {};
typedef B MyB;
MyB : B
typedef
-> B
B
Class
-> MyB
Class Designer does not support displaying this kind of relationship by using a context menu command.
#include <vector>
std::vector<T>
Class
MyIntVect : std::vector<int>
typedef
MyVect
Class
-> MyIntVect
See Also
Working with Visual C++ Code (Class Designer)
typedef Specifier
Additional Information About Class Designer Errors
10/18/2017 • 1 min to read • Edit Online
Class Designer does not track the location of your source files, so modifying your project structure or moving
source files in the project can cause Class Designer to lose track of the type (especially the source type of a typedef,
base classes, or association types). You might receive an error such as Class Designer is unable to display this
type. If you do, drag the modified or relocated source code to the class diagram again to redisplay it.
You can find assistance with other errors and warnings in the following resources:
Working with Visual C++ Code (Class Designer)
Includes troubleshooting information about displaying C++ in a class diagram.
Visual Studio Class Designer Forum
Provides a forum for questions about the Class Designer.
See Also
Designing and Viewing Classes and Types
Setting Bookmarks in Code
10/18/2017 • 1 min to read • Edit Online
You can use bookmarks to mark lines in your code so that you can quickly return to a specific location and jump
back and forth between locations.
Bookmark commands and icons are available in two places: the bookmark window (View/Bookmark Window)
and the text editor toolbar.
Managing Bookmarks
To add a bookmark, place the cursor on the line you want to bookmark. Click the Toggle button, or press CTRL+K.
This adds the bookmark. If you click the Toggle button (or press CTRL+K) again, the bookmark is removed. You can
also delete bookmarks by clicking the Delete button in the bookmark window.
IMPORTANT
The bookmark is set to the line number, not to the code. If you modify the code, the bookmark is retained at the line
number, and does not move with the code.
You can navigate between bookmarks by using the Next Bookmark and Previous Bookmark buttons in the
bookmark window.
You can organize bookmarks into virtual folders by clicking New Folder in the bookmark window and then
dragging selected bookmarks into the new folder.
You can turn off bookmarks (without removing them) by clicking the Disable All Bookmarks button in the
bookmark window. You can re-enable them by clicking the same button (which is now called Enable All
Bookmarks).
Using the Task List
10/18/2017 • 3 min to read • Edit Online
Use the Task List to track code comments that use tokens such as TODO and HACK , or custom tokens, and to
manage shortcuts that will take you directly to a predefined location in the code. Click on the item in the list to go to
its location in the source code.
In this topic:
The Task List window
User Tasks
Tokens and comments
Custom tokens
C++ TODO comments
Shortcuts
User Tasks
The user task feature has been removed in Visual Studio 2015. When you open a solution which has user task data
from Visual Studio 2013 and earlier in Visual Studio 2015, the user task data in your .suo file will not be affected,
but the user tasks will not be displayed in the task list.
If you wish to continue to access and update your user task data, you should open the project in Visual Studio 2013
and copy the content of any user tasks into your preferred project management tool (such as Team Foundation
Server).
Because TODO is a predefined token, this comment appears as a TODO task in the list.
Custom tokens
By default, Visual Studio includes the following tokens: HACK, TODO, UNDONE, NOTE. These are not case sensitive.
You can also create your own custom tokens.
To c r e a t e a c u st o m t o k e n
3. In the Tokens category, in the Name text box, enter your token name, for example "BUG".
4. In the Priority drop-down list, choose a default priority for the new token. Choose the Add button.
C++ TODO comments
By default, C++ TODO comments are displayed in the Task List window. You can change this behavior.
To t u r n o ff C + + T O D O c o m m e n t s
1. On the Tools menu, go to Options | Text Editor | C/C++ | View | Enumerate Comment Tasks and set
the value to false.
2. In the Options dialog box, open Text Editor.
3. Under C/C++, choose View, and then set Enumerate Comment Tasks to False.
Shortcuts
A shortcut is a bookmark in the code that is tracked in the Task List; it has a different icon than a regular bookmark.
Double-click the shortcut in the Task List to go to the corresponding location in the code.
To create a shortcut
Insert the pointer into the code where you want to place a shortcut. Choose Edit | Bookmarks | Add Task
List Shortcut or press (Keyboard: Ctrl+K, Ctrl+H).
To navigate through the shortcuts in the code, choose a shortcut in the list, and then choose Next Task or
Previous Task from the shortcut menu.
See Also
Task List, Environment, Options Dialog Box
Find code changes and other history with CodeLens
10/18/2017 • 8 min to read • Edit Online
Stay focused on your work while you find out what happened to your code - without leaving the editor. Find
references and changes to your code, linked bugs, work items, code reviews, and unit tests.
NOTE
CodeLens is available only in Visual Studio Enterprise and Visual Studio Professional editions. It is not available in Visual
Studio Community edition.
See where and how the individual parts of your code are used in your solution:
Contact your team about changes to your code without leaving the editor:
To choose the indicators that you want to see, or to turn CodeLens off and on, go to Tools, Options, Text Editor,
All Languages, CodeLens.
For all other types of files that you can open in the Visual Studio editor, you get CodeLens details for the
entire file in one place at the bottom of the window (file-level indicators).
To use the keyboard to select indicators, press and hold the ALT key to display the related number keys.
The default time period is the last 12 months. If your code is stored in Team Foundation Server, you can change
this by running the TFSConfig command with the CodeIndex command and the /indexHistoryPeriod flag.
To see a detailed history of all the changes, including those from more than a year ago, choose Show all file
changes.
When your files are in a Git repository and you choose the code-element-level changes indicator, this is what you
see.
Find changes for an entire file (except for C# and Visual Basic files) in the file-level indicators at the bottom of the
window.
To get more details about a change, right-click that item. Depending on whether you are using TFVC or Git you get
a series of options to compare the versions of the file, view details and track the changeset, get the selected version
of the file, and email the author of that change. Some of these details appear in Team Explorer.
You can also see who changed your code over time. This can help you find patterns in your team's changes and
assess their impact.
Find how many people changed your code and how many changes were made (Alt + 6) in your main branch:
You can review this change without leaving your current branch (Main):
For example, your code in the Main branch now has the bug fix from the Dev branch:
A child branch
A peer branch
Open the shortcut menu for an item to see the contact options. If you have Lync or Skype for Business installed,
you see these options:
4. To review a test's definition, double-click the test item in the CodeLens indicator window to open the code
file in the editor.
5. Review the test's results. Choose the test status indicator ( or ), or press Alt + 1.
6. To see how many people changed this test, who changed this test, or how many changes were made to this
test, Find your code's history and linked items.
Q&A
Q: How do I turn CodeLens off or on? Or choose which indicators to see?
A: You can turn indicators off or on, except for the references indicator. Go to Tools, Options, Text Editor, All
Languages, CodeLens.
When the indicators are turned on, you can also open the CodeLens options from the indicators.
Turn CodeLens file-level indicators on and off using the chevron icons at the bottom of the editor window.
Q: Where is CodeLens?
A: CodeLens appears in Visual C# .NET and Visual Basic .NET code at the method, class, indexer, and property level.
CodeLens appears at the file level for all other types of files.
Make sure CodeLens is turned on. Go to Tools, Options, Text Editor, All Languages, CodeLens.
If your code is stored in TFS, make sure that code indexing is turned on by using the CodeIndex command
with the TFS Config command.
TFS-related indicators appear only when work items are linked to the code and when you have permissions
to open linked work items. Confirm that you have team member permissions.
Unit test indicators don't appear when application code doesn't have unit tests. Test status indicators appear
automatically in test projects. If you know that your application code has unit tests, but the test indicators
don't appear, try building the solution (Ctrl + Shift + B).
Q: Why don't I see the work item details for a commit?
A: This might happen because CodeLens can't find the work items in TFS. Check that you're connected to the team
project that has those work items and that you have permissions to see those work items. This might also happen
if the commit description has incorrect information about the work item IDs in TFS.
Q: Why don't I see the Lync or Skype indicators?
A: They don't appear if you're not signed into Lync or Skype for Business, don't have one of these installed, or
don't have a supported configuration. But you can still send mail:
Use the CodeIndex command to manage code indexing on Team Foundation Server. For example, you might
want to reset the index to fix CodeLens information, or turn off indexing to investigate server performance issues.
Required Permissions
To use the CodeIndex command, you must be a member of the Team Foundation Administrators security
group. See Permissions and groups defined for Team Services and TFS.
NOTE
Even if you log on with administrative credentials, you must open an elevated Command Prompt window to run this
command. You must also run this command from the application tier for Team Foundation.
Syntax
TFSConfig CodeIndex /indexingStatus | /setIndexing:[ on | off | keepupOnly ] | /ignoreList:[ add | remove |
removeAll | view ] ServerPath | /listLargeFiles [/fileCount:FileCount] [/minSize:MinSize] | /reindexAll |
/destroyCodeIndex [/noPrompt] | /temporaryDataSizeLimit:[ view | <SizeInGBs> | disable ] |
/indexHistoryPeriod:[ view | all | <NumberOfMonths> ] [/collectionName:CollectionName |
/collectionId:CollectionId]
Parameters
ARGUMENT DESCRIPTION
CollectionName Specifies the name of the team project collection. If the name
has spaces, enclose the name with quotation marks, for
example, "Fabrikam Web Site".
OPTION DESCRIPTION
/ignoreList:[ add | remove | removeAll | view ] ServerPath Specifies a list of code files and their paths that you don't
want indexed.
You can use the wildcard character (*) at the start, end, or
both ends of the server path. - add: Add the file that you don't want indexed to the
ignored file list.
- remove: Remove the file that you want indexed from the
ignored file list.
- removeAll: Clear the ignored file list and start indexing all
files.
- view: See all the files that aren't being indexed.
/listLargeFiles [/fileCount: FileCount /minSize: Shows the specified number of files that exceeds the specified
MinSize ] size in KB. You can then use the /ignoreList option to exclude
these files from indexing.
/destroyCodeIndex [/noPrompt] Delete the code index and remove all indexed data. Does not
require confirmation if you use the /noPrompt option.
/temporaryDataSizeLimit:[ view | < SizeInGBs > | disable ] Control how much temporary data that CodeLens creates
when processing changesets. The default limit is 2 GB.
/indexHistoryPeriod:[ view | all | < NumberOfMonths >] Control how long to index your change history. This affects
how much history CodeLens shows you. The default limit is
12 months. This means CodeLens shows your change history
from the last 12 months only.
/collectionName: CollectionName Specifies the name of the team project collection on which to
run the CodeIndex command. Required if you don't use
/CollectionId.
Examples
NOTE
The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted
herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person,
places, or events is intended or should be inferred.
To stop indexing previously created changesets and start indexing new changesets only:
To exclude a specific file from indexing and add it to the ignored file list:
To remove the size limit on CodeLens temporary data and continue indexing regardless of temporary data size:
Running a build creates assemblies and executable applications from your source code at any point during a
development cycle. In general, the build process is very similar across many different project types such as
Windows, ASP.NET, mobile apps, and others. The build process is also very similar across programming
languages such as C#, Visual Basic, C++, and F#.
By building your code often, you can quickly identify compile-time errors, such as incorrect syntax, misspelled
keywords, and type mismatches. You can also quickly detect and correct run-time errors, such as logic errors and
semantic errors, by frequently building and running debug versions of the code.
A successful build is essentially a validation that the application's source code contains correct syntax and that all
static references to libraries, assemblies, and other components have been resolved. This produces an application
executable that can then be tested for proper functioning in both a debugging environment and through a variety
of manual and automated tests to validate code quality. Once the application has been fully tested, you can then
compile a release version to deploy to your customers. For an introduction to this process, see Walkthrough:
Building an Application.
Within the Visual Studio product family, there are three methods you can use to build an application: the Visual
Studio IDE, the MSBuild command-line tools, and Team Foundation Build on Visual Studio Team Services:
The documentation in this section goes into further details of the IDE-based build process. For more information
on the other methods, see MSBuild and Continuous integration and deployment, respectively.
See Also
Building (Compiling) Web Site Projects
Walkthrough: Building an Application
10/18/2017 • 5 min to read • Edit Online
By completing this walkthrough, you'll become more familiar with several options that you can configure when
you build applications with Visual Studio. You'll create a custom build configuration, hide certain warning
messages, and increase build output information for a sample application.
This topic contains the following sections:
Install the Sample Application
Create a Custom Build Configuration
Build the Application
Hide Compiler Warnings
Display Additional Build Details in the Output Window
Create a Release Build
7. Choose Close.
You can quickly verify or change the active solution configuration by using the Solution Configurations list on
the Standard toolbar.
Build the Application
Next, you'll build the solution with the custom build configuration.
To build the solution
On the menu bar, choose Build, Build Solution.
The Output window displays the results of the build. The build succeeded.
You can temporarily hide certain warning messages during a build rather than have them clutter up the build
output.
To hide a specific Visual C# warning
1. In Solution Explorer, choose the top-level project node.
2. On the menu bar, choose View, Property Pages.
The Project Designer opens.
3. Choose the Build page and then, in the Suppress warnings box, specify the warning number 0168.
IMPORTANT
If you display more information, the build will take longer to complete.
TIP
You can search the contents of the Output window if you display the Find dialog box by choosing the Ctrl+F keys.
For more information, see How to: View, Save, and Configure Build Log Files.
IMPORTANT
A message box might appear, warning you that the network share that you've specified might not be a trusted
location. If you trust the location that you've specified, choose the OK button in the message box.
IMPORTANT
A message box might appear, warning you that the network share that you've specified might not be a trusted
location. If you trust the location that you've specified, choose the OK button in the message box.
6. On the Standard toolbar, set the Solution Configurations to Release and the Solution Platforms to x86.
7. Build the application.
The executable file is copied to the network path that you specified. Its path would be
\\myserver\builds\FileName.exe.
Congratulations: you've successfully completed this walkthrough.
See Also
Walkthrough: Building a Project (C++)
ASP.NET Web Application Project Precompilation Overview
Walkthrough: Using MSBuild
Building and Cleaning Projects and Solutions in
Visual Studio
10/18/2017 • 2 min to read • Edit Online
By using the procedures in this topic, you can build, rebuild, or clean all or some of the projects or project items in
a solution. For a step-by-step tutorial, see Walkthrough: Building an Application.
NOTE
The UI in your edition of Visual Studio might differ from what this topic describes, depending on your active settings. To
change your settings, open the Tools menu, and then choose Import and Export Settings. For more information, see
Personalize the Visual Studio IDE.
NOTE
The Build command becomes Build Solution when a solution includes more than one project.
Choose Rebuild Solution to "clean" the solution and then build all project files and components.
Choose Clean Solution to delete any intermediate and output files. With only the project and
component files left, new instances of the intermediate and output files can then be built.
To build or rebuild a single project
1. In Solution Explorer, choose or open the project.
2. On the menu bar, choose Build, and then choose either BuildProjectName or RebuildProjectName.
Choose BuildProjectName to build only those project components that have changed since the
most recent build.
Choose RebuildProjectName to "clean" the project and then build the project files and all project
components.
To build only the startup project and its dependencies
1. On the menu bar, choose Tools, Options.
2. In the Options dialog box, expand the Projects and Solutions node, and then choose the Build and Run
page.
The Build and Run, Projects and Solutions, Options dialog box opens.
3. Select the Only build startup projects and dependencies on Run check box.
When this check box is selected, only the current startup project and its dependencies are built when you
perform either of the following steps:
On the menu bar, choose Debug, Start (F5).
On the menu bar, choose Build, Build Solution (CTRL+SHIFT+B).
When this check box is cleared, all projects, their dependencies, and the solution files are built when
you run either of the preceding commands. By default, this check box is cleared.
To build only the selected Visual C++ project
1. Choose a Visual C++ project, and then, on the menu bar, choose Build, Project Only, and one of the
following commands:
Build Only ProjectName
Rebuild Only ProjectName
Clean Only ProjectName
Link Only ProjectName
These commands apply only to the Visual C++ project that you chose, without building, rebuilding,
cleaning, or linking any project dependencies or solution files. Depending on your version of Visual
Studio, the Project Only submenu might contain more commands.
To compile multiple C++ project items
1. In Solution Explorer, choose multiple files that have can be compiled actions, open the shortcut menu for
one of those files, and then choose Compile.
If the files have dependencies, the files will be compiled in dependency order. The compile operation will
fail if the files require a precompiled header that isn't available when you compile. The compile operation
uses the current active solution configuration.
To stop a build
1. Perform either of the following steps:
On the menu bar, choose Build, Cancel.
Choose the Ctrl + Break keys.
See Also
How to: View, Save, and Configure Build Log Files
Obtaining Build Logs
Compiling and Building
Understanding Build Configurations
Debug and Release Project Configurations
C/C++ Building Reference
Devenv Command Line Switches
Solutions and Projects
How to: Change the Build Output Directory
10/18/2017 • 1 min to read • Edit Online
You can specify the location of output on a per-configuration basis (for debug, release, or both) generated by your
project.
NOTE
If you have a Setup project see the note at the end of this article.
NOTE
In a Setup Project, the Output file name box changes only the location of the Setup.exe file, not the location of the project
files. For more information, see Build, Configuration Properties, Deployment Project Properties Dialog Box.
See Also
Build Page, Project Designer (C#)
General Property Page (Project)
Compiling and Building
How to: Build to a Common Output Directory
10/18/2017 • 1 min to read • Edit Online
By default, Visual Studio builds each project in a solution in its own folder inside the solution. You can change the
build output paths of your projects to force all outputs to be placed in the same folder.
To place all solution outputs in a common directory
1. Click on one project in the solution.
2. On the Project menu, click Properties.
3. Depending on the type of project, click on either the Compile tab or the Build tab, and set the Output path
to a folder to use for all projects in the solution.
4. Repeat steps 1-3 for all projects in the solution.
See Also
Compiling and Building
How to: Change the Build Output Directory
Specifying Custom Build Events in Visual Studio
10/18/2017 • 1 min to read • Edit Online
By specifying a custom build event, you can automatically run commands before a build starts or after it finishes.
For example, you can run a .bat file before a build starts or copy new files to a folder after the build is complete.
Build events run only if the build successfully reaches those points in the build process.
For specific information about the programming language that you're using, see the following topics:
Visual Basic--How to: Specify Build Events (Visual Basic).
Visual C# and F#--How to: Specify Build Events (C#).
Visual C++--Specifying Build Events.
Syntax
Build events follow the same syntax as DOS commands, but you can use macros to create build events more easily.
For a list of available macros, see Pre-build Event/Post-build Event Command Line Dialog Box.
For best results, follow these formatting tips:
Add a call statement before all build events that run .bat files.
Example: call C:\MyFile.bat
NOTE
%I in the code above should be %%I in batch scripts.
See Also
Compiling and Building
Pre-build Event/Post-build Event Command Line Dialog Box
MSBuild Special Characters
Walkthrough: Building an Application
How to: Set Multiple Startup Projects
10/18/2017 • 1 min to read • Edit Online
Visual Studio allows you to specify how more than one project is run when you start the debugger.
To set multiple startup projects
1. In the Solution Explorer, select the solution (the very top node).
2. Choose the solution node's context (right-click) menu and then choose Properties. The Solution Property
Pages dialog box appears.
3. Expand the Common Properties node, and choose Startup Project.
4. Choose the Multiple Startup Projects option and set the appropriate actions.
See Also
Compiling and Building
Creating Solutions and Projects
Managing Project and Solution Properties
How to: Create and Remove Project Dependencies
10/18/2017 • 1 min to read • Edit Online
When building a solution that contains multiple projects, it can be necessary to build certain projects first, to
generate code used by other projects. When a project consumes executable code generated by another project, the
project that generates the code is referred to as a project dependency of the project that consumes the code. Such
dependency relationships can be defined in the Project Dependencies Dialog Box.
To assign dependencies to projects
1. In Solution Explorer, select a project.
2. On the Project menu, choose Project Dependencies.
The Project Dependencies dialog box opens.
NOTE
The Project Dependencies option is only available in a solution with more than one project.
3. On the Dependencies tab, select a project from the Project drop-down menu.
4. In the Depends on field, select the check box of any other project that must build before this project does.
Your solution must consist of more than one project before you can create project dependencies.
To remove dependencies from projects
1. In Solution Explorer, select a project.
2. On the Project menu, choose Project Dependencies.
The Project Dependencies dialog box opens.
NOTE
The Project Dependencies option is only available in a solution with more than one project.
3. On the Dependencies tab, select a project from the Project drop-down menu.
4. In the Depends on field, clear the check boxes beside any other projects that are no longer dependencies of
this project.
See Also
Building and Cleaning Projects and Solutions in Visual Studio
Compiling and Building
Understanding Build Configurations
Managing Project and Solution Properties
How to: View, Save, and Configure Build Log Files
10/18/2017 • 2 min to read • Edit Online
After you build a project in the Visual Studio IDE, you can view information about that build in the Output
window. By using this information, you can, for example, troubleshoot a build failure. For C++ projects, you can
also view the same information in a .txt file that's created and saved automatically. For managed-code projects,
you can copy and paste the information from the Output window into a .txt file and save it yourself. You can also
use the IDE to specify what kinds of information you want to view about each build.
If you build any kind of project by using MSBuild, you can create a .txt file to save information about the build. For
more information, see Obtaining Build Logs.
To view the build log file for a C++ project
1. In Windows Explorer or File Explorer, open the following file: \...\Visual Studio
Version\Projects\ProjectName\ProjectName\Debug\ProjectName.txt
To create a build log file for a managed-code project
1. On the menu bar, choose Build, Build Solution.
2. In the Output window, highlight the information from the build, and then copy it to the Clipboard.
3. Open a text editor, such as Notepad, paste the information into the file, and then save it.
To change the amount of information included in the build log
1. On the menu bar, choose Tools, Options.
2. On the Projects and Solutions page, choose the Build and Run page.
3. In the MSBuild project build output verbosity list, choose one of the following values, and then choose
the OK button.
Diagnostic Displays all data that's available for the build. You can use
this level of detail to help debug issues with custom build
scripts and other build issues.
For more information, see Options Dialog Box, Projects and Solutions, Build and Run and LoggerVerbosity.
IMPORTANT
You must rebuild the project for your changes to take effect in the Output window (all projects) and the
ProjectName.txt file (C++ projects only).
See Also
Obtaining Build Logs
Building and Cleaning Projects and Solutions in Visual Studio
Compiling and Building
How to: Exclude Projects from a Build
10/18/2017 • 1 min to read • Edit Online
You can build a solution without building all projects that it contains. For example, you might exclude a project that
breaks the build. You could then build the project after you investigate and address the issues.
You can exclude a project by taking the following approaches:
Removing it temporarily from the active solution configuration.
Creating a solution configuration that doesn't include the project.
For more information, see Understanding Build Configurations.
To temporarily remove a project from the active solution configuration
1. On the menu bar, choose Build, Configuration Manager.
2. In the Project contexts table, locate the project you want to exclude from the build.
3. In the Build column for the project, clear the check box.
4. Choose the Close button, and then rebuild the solution.
To create a solution configuration that excludes a project
1. On the menu bar, choose Build, Configuration Manager.
2. In the Active solution configuration list, choose <New>.
3. In the Name box, enter a name for the solution configuration.
4. In the Copy settings from list, choose the solution configuration on which you want to base the new
configuration (for example, Debug), and then choose the OK button.
5. In the Configuration Manager dialog box, clear the check box in the Build column for the project that you
want to exclude, and then choose the Close button.
6. On the Standard toolbar, verify that the new solution configuration is the active configuration in the
Solution Configurations box.
7. On the menu bar, choose Build, Rebuild Solution.
See Also
Understanding Build Configurations
How to: Create and Edit Configurations
How to: Build Multiple Configurations Simultaneously
How to: Suppress Compiler Warnings
10/18/2017 • 2 min to read • Edit Online
You can declutter a build log by specifying one or more kinds of compiler warnings that you don't want it to
contain. For example, you might use this technique to review some but not all of the information that's generated
automatically when you set the build-log verbosity to Normal, Detailed, or Diagnostic. For more information about
verbosity, see How to: View, Save, and Configure Build Log Files.
To suppress specific warnings for Visual C# or F#
1. In Solution Explorer, choose the project in which you want to suppress warnings.
2. On the menu bar, choose View, Property Pages.
3. Choose the Build page.
4. In the Suppress warnings box, specify the error codes of the warnings that you want to suppress,
separated by semicolons, and then rebuild the solution.
To suppress specific warnings for Visual C++
1. In Solution Explorer, choose the project or source file in which you want to suppress warnings.
2. On the menu bar, choose View, Property Pages.
3. Choose the Configuration Properties category, choose the C/C++ category, and then choose the
Advanced page.
4. Perform one of the following steps:
In the Disable Specific Warnings box, specify the error codes of the warnings that you want to
suppress, separated by a semicolon.
In the Disable Specific Warnings box, choose Edit to display more options.
5. Choose the OK button, and then rebuild the solution.
5. Add one or more warning numbers as the value of the <NoWarn> element. If you specify multiple warning
numbers, separate them with a comma, as the following example shows.
See Also
Walkthrough: Building an Application
How to: View, Save, and Configure Build Log Files
Compiling and Building
Understanding Build Configurations
10/18/2017 • 4 min to read • Edit Online
You can store different configurations of solution and project properties to use in different kinds of builds. To
create, select, modify, or delete a configuration, you can use the Configuration Manager. To open it, on the
menu bar, choose Build, Configuration Manager, or just type Configuration in the Quick Launch box. You
can also use the Solution Configurations list on the Standard toolbar to select a configuration or open the
Configuration Manager.
NOTE
If you can't find solution configuration settings on the toolbar and can't access the Configuration Manager, Visual Basic
development settings may be applied. For more information, see How to: Manage Configurations with Visual Basic
Developer Settings Applied.
By default, Debug and Release configurations are included in projects that are created by using Visual Studio
templates. A Debug configuration supports the debugging of an app, and a Release configuration builds a
version of the app that can be deployed. For more information, see How to: Set Debug and Release
Configurations. You can also create custom solution configurations and project configurations. For more
information, see How to: Create and Edit Configurations.
Solution Configurations
A solution configuration specifies how projects in the solution are to be built and deployed. To modify a solution
configuration or define a new one, in the Configuration Manager, under Active solution configuration,
choose Edit or New.
Each entry in the Project contexts box in a solution configuration represents a project in the solution. For every
combination of Active solution configuration and Active solution platform, you can set how each project is
used. (For more information about solution platforms, see Understanding Build Platforms.)
NOTE
When you define a new solution configuration and select the Create new project configurations check box, Visual
Studio automatically assigns the new configuration to all of the projects. Likewise, when you define a new solution platform
and select the Create new project platforms check box, Visual Studio automatically assigns the new platform to all of the
projects. Also, if you add a project that targets a new platform, Visual Studio adds that platform to the list of solution
platforms and assigns it to all of the projects.
You can still modify the settings for each project.
The active solution configuration also provides context to the IDE. For example, if you're working on a project and
the configuration specifies that it will be built for a mobile device, the Toolbox displays only items that can be
used in a mobile device project.
Project Configurations
The configuration and platform that a project targets are used together to specify the properties to use when it's
built. A project can have a different set of property definitions for each combination of configuration and
platform. To modify the properties of a project, you can use its Property Pages. (In Solution Explorer, open the
shortcut menu for the project and then choose Properties.)
For each project configuration, you can define configuration-dependent properties as needed. For example, for a
particular build, you can set which project items will be included, and what output files will be created, where
they will be put, and how they will be optimized.
Project configurations can differ considerably. For example, the properties of one configuration might specify
that its output file be optimized to occupy the minimum space, while another configuration might specify that its
executable runs at the maximum speed.
Project configurations are stored by solution—not by user—so that they can be shared by a team.
Although project dependencies are configuration-independent, only the projects that are specified in the active
solution configuration will be built.
See Also
Walkthrough: Building an Application
Compiling and Building
Solutions and Projects
C/C++ Building Reference
Devenv Command Line Switches
How to: Create and Edit Configurations
10/18/2017 • 3 min to read • Edit Online
You can create several build configurations for a solution. For example, you can configure a debug build that your
testers can use to find and fix problems, and you can configure different kinds of builds that you can distribute to
different customers.
> [!NOTE] > Your computer might show different names or locations for some of the Visual Studio user interface
elements in the following instructions. The Visual Studio edition that you have and the settings that you use
determine these elements. For more information, see Personalizing the IDE.
NOTE
If the Configuration Manager command doesn't appear on the shortcut menu, look under the Build menu on the
menu bar. If it doesn't appear there either, on the menu bar, choose Tools, Options, and then in the left pane of the
Options dialog box, expand Projects and Solutions, General, and in the right pane, select the Show advanced
build configurations check box.
In the Configuration Manager dialog box, you can use the Active solution configuration drop-down
list to select a solution-wide build configuration, modify an existing one, or create a new configuration. You
can use the Active solution platform drop-down list to select the platform that the configuration targets,
modify an existing one, or add a new platform. The Project contexts pane lists the projects in the solution.
For each project, you can select a project-specific configuration and platform, modify existing ones, or
create a new configuration or add a new platform. You can also select check boxes that indicate whether
each project is included when you use the solution-wide configuration to build or deploy the solution.
After you set up the configurations you want, you can set project properties that are appropriate for those
configurations.
To set properties based on configurations
In Solution Explorer, open the shortcut menu for a project and then choose Properties.
The Property Pages window opens.
You can set properties for your configurations. For example, for a Release configuration, you can specify
that code is optimized when the solution is built, and for a Debug configuration, you can specify that the
DEBUG conditional compilation symbol is included. For more information about property page settings, see
Managing Project and Solution Properties.
By default, all advanced build configuration options are hidden with Visual Basic Developer settings applied. This
topic explains how to manually enable these settings.
NOTE
The General node is visible even if the Show all settings option is unchecked. If you want to see every option
available, click Show all settings.
See Also
Understanding Build Configurations
Compiling and Building
How to: Build Multiple Configurations Simultaneously
10/18/2017 • 1 min to read • Edit Online
You can build most types of projects with multiple, or even all, of their build configurations at the same time by
using the Batch Build dialog box. However, you can't build the following types of projects in multiple build
configurations at the same time:
1. Windows 8.x Store apps built for Windows using JavaScript.
2. All Visual Basic projects.
For more information about build configurations, see Understanding Build Configurations.
To build a project in multiple build configurations
1. On the menu bar, choose Build, Batch Build.
2. In the Build column, select the check boxes for the configurations in which you want to build a project.
TIP
To edit or create a build configuration for a solution, choose Build, Configuration Manager on the menu bar to
open the Configuration Manager dialog box. After you have edited a build configuration for a solution, choose the
Rebuild button in the Batch Build dialog box to update all build configurations for the projects in the solution.
3. Choose the Build or Rebuild buttons to build the project with the configurations that you specified.
See Also
How to: Create and Edit Configurations
Understanding Build Configurations
Building Multiple Projects in Parallel
Understanding Build Platforms
10/18/2017 • 1 min to read • Edit Online
You can store different versions of solution and project properties that apply to different target platforms. For
example, you can create a Debug configuration that targets an x86 platform and a Debug configuration that
targets an x64 platform. You can quickly change the active platform so that you can easily build multiple
configurations.
In This Section
How to: Configure Projects to Target Platforms
Explains how to configure a project to target a specific platform.
How to: Configure Projects to Target Multiple Platforms
Explains how to configure a project to target multiple platforms.
See Also
Walkthrough: Building an Application
Building and Cleaning Projects and Solutions in Visual Studio
Compiling and Building
How to: Configure Projects to Target Platforms
10/18/2017 • 1 min to read • Edit Online
Visual Studio enables you to set up your applications to target different platforms, including 64-bit platforms. For
more information on 64-bit platform support in Visual Studio, see 64-bit Applications.
NOTE
If you give your configuration a new name, you may have to modify the settings in the Project Designer to
target the correct platform.
c. If you want to copy the settings from a current platform configuration, choose it, and then choose the
OK button.
The properties for all projects that target the 64-bit platform are updated, and the next build of the project
will be optimized for 64-bit platforms.
See Also
Understanding Build Platforms
/platform (C# Compiler Options)
64-bit Applications
Visual Studio IDE 64-Bit Support
How to: Configure Projects to Target Multiple
Platforms
10/18/2017 • 2 min to read • Edit Online
Visual Studio provides a way for a solution to target several different CPU architectures, or platforms, at once. The
properties to set these are accessed through the Configuration Manager dialog box.
Targeting a Platform
The Configuration Manager dialog box allows you to create and set solution-level and project-level
configurations and platforms. Each combination of solution-level configurations and targets can have a unique set
of properties associated with it, allowing you to easily switch between, for example, a Release configuration that
targets an x64 platform, a Release configuration that targets an x86 platform, and a Debug configuration that
targets an x86 platform.
To set your configuration to target a different platform
1. On the Build menu, click Configuration Manager.
2. In the Active solution platform box, select the platform you want your solution to target, or select
<New> to create a new platform. Visual Studio will compile your application to target the platform that is
set as the active platform in the Configuration Manager dialog box.
Removing a Platform
If you realize that you have no need for a platform, you can remove it using the Configuration Manager dialog box.
This will remove all solution and project settings that you configured for that combination of configuration and
target.
To remove a platform
1. On the Build menu, click Configuration Manager.
2. In the Active solution platform box, select <Edit>. The Edit Solution Platforms dialog box opens.
3. Click the platform you want to remove, and click Remove.
See Also
How to: Create and Edit Configurations
Understanding Build Configurations
Building and Cleaning Projects and Solutions in Visual Studio
How to: Specify Build Events (Visual Basic)
10/18/2017 • 4 min to read • Edit Online
Build events in Visual Basic can be used to run scripts, macros, or other actions as a part of the compilation
process. Pre-build events occur before compilation; post-build events occur after compilation.
Build events are specified in the Build Events dialog box, available from the Compile page of the Project
Designer.
NOTE
Visual Basic Express does not support entry of build events. This is supported only in the full Visual Studio product.
NOTE
Add a call statement before all post-build commands that run .bat files. For example, call C:\MyFile.bat or
call C:\MyFile.bat call C:\MyFile2.bat .
NOTE
If your pre-build or post-build event does not complete successfully, you can terminate the build by having your
event action exit with a code other than zero (0), which indicates a successful action.
<dependentOS>
<osVersionInfo>
<os majorVersion="4" minorVersion="10" buildNumber="0" servicePackMajor="0" />
</osVersionInfo>
</dependentOS>
Imports System.Xml
Sub Main()
Dim applicationManifestPath As String
applicationManifestPath = My.Application.CommandLineArgs(0)
Console.WriteLine("Application Manifest Path: " & applicationManifestPath.ToString)
document.Save(applicationManifestPath)
End Sub
The command takes two arguments. The first argument is the path to the application manifest (that is, the
folder in which the build process creates the manifest, typically Projectname.publish). The second argument
is the new operating system version.
5. On the Build menu, click Build Solution.
6. Copy the .exe file to a directory such as C:\TEMP\ChangeOSVersionVB.exe .
Next, invoke this command in a post-build event to change the application manifest.
To invoke a post-build event to change the application manifest
1. Create a Windows application for the project to be published. From the File menu, click New, and then click
Project.
2. In the New Project dialog box, in the Visual Basic node, select Windows Classic Desktop and then the
Windows Forms App template. Name the project VBWinApp .
3. With the project selected in Solution Explorer, on the Project menu, click Properties.
4. In the Project Designer, go to the Publish page and set Publishing location to C:\TEMP\ .
5. Publish the project by clicking Publish Now.
The manifest file will be built and put in C:\TEMP\VBWinApp_1_0_0_0\VBWinApp.exe.manifest . To view the
manifest, right-click the file and click Open with, then click Select the program from a list, and then click
Notepad.
Search in the file for the <osVersionInfo> element. For example, the version might be:
6. In the Project Designer, go to the Compile tab and click the Build Events button to open the Build Events
dialog box.
7. In the Post-build Event Command Line box, enter the following command:
C:\TEMP\ChangeOSVersionVB.exe "$(TargetPath).manifest" 5.1.2600.0
When you build the project, this command will change the minimum operating system version in the
application manifest to 5.1.2600.0.
The $(TargetPath) macro expresses the full path for the executable being created. Therefore,
$(TargetPath).manifest will specify the application manifest created in the bin directory. Publishing will copy
this manifest to the publishing location that you set earlier.
8. Publish the project again. Go to the Publish page and click Publish Now.
View the manifest again. To view the manifest, go to the publish directory, right-click the file and click Open
with and then Select the program from a list, and then click Notepad.
The version should now read:
See Also
Managing Compilation Properties
Compile Page, Project Designer (Visual Basic)
Publish Page, Project Designer
Pre-build Event/Post-build Event Command Line Dialog Box
How to: Specify Build Events (C#)
How to: Specify Build Events (C#)
10/18/2017 • 5 min to read • Edit Online
Use build events to specify commands that run before the build starts or after the build finishes. Build events are
executed only if the build successfully reaches those points in the build process.
When a project is built, pre-build events are added to a file that is named PreBuildEvent.bat and post-build events
are added to a file that is named PostBuildEvent.bat. If you want to ensure error checking, add your own error-
checking commands to the build steps.
> [!NOTE] > Your computer might show different names or locations for some of the Visual Studio user interface
elements in the following instructions. The Visual Studio edition that you have and the settings that you use
determine these elements. For more information, see Personalizing the IDE.
NOTE
Pre-build events do not run if the project is up to date and no build is triggered.
5. In the Post-build event command line box, specify the syntax of the build event.
NOTE
Add a call statement before all post-build commands that run .bat files. For example, call C:\MyFile.bat or
call C:\MyFile.bat call C:\MyFile2.bat .
6. In the Run the post-build event box, specify under what conditions to run the post-build event.
NOTE
To add lengthy syntax, or to select any build macros from the Pre-build Event/Post-build Event Command Line
Dialog Box, click the Ellipsis button (...) to display an edit box.
The build event syntax can include any command that is valid at a command prompt or in a .bat file. The
name of a batch file should be preceded by call to ensure that all subsequent commands are executed.
Note If your pre-build or post-build event does not complete successfully, you can terminate the build by
having your event action exit with a code other than zero (0), which indicates a successful action.
<dependentOS>
<osVersionInfo>
<os majorVersion="4" minorVersion="10" buildNumber="0" servicePackMajor="0" />
</osVersionInfo>
</dependentOS>
using System.Xml;
4. In the ChangeOSVersionCS namespace, replace the Program class implementation with the following code:
class Program
{
/// <summary>
/// This function will set the minimum operating system version for a ClickOnce application.
/// </summary>
/// <param name="args">
/// Command Line Arguments:
/// 0 - Path to application manifest (.exe.manifest).
/// 1 - Version of OS
///</param>
static void Main(string[] args)
{
string applicationManifestPath = args[0];
Console.WriteLine("Application Manifest Path: " + applicationManifestPath);
XmlDocument document;
XmlNamespaceManager namespaceManager;
namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
namespaceManager.AddNamespace("asmv2", "urn:schemas-microsoft-com:asm.v2");
string baseXPath;
baseXPath = "/asmv1:assembly/asmv2:dependency/asmv2:dependentOS/asmv2:osVersionInfo/asmv2:os";
document.Save(applicationManifestPath);
}
}
The command takes two arguments: the path of the application manifest (that is, the folder in which the
build process creates the manifest, typically Projectname.publish), and the new operating system version.
5. Build the project. On the Build menu, click Build Solution.
6. Copy the .exe file to a directory such as C:\TEMP\ChangeOSVersionVB.exe .
Next, invoke this command in a post-build event to modify the application manifest.
To invoke a post-build event to modify the application manifest
1. Create a Windows application for the project to be published. From the File menu, point to New, and then
click Project.
2. In the New Project dialog box, expand Visual C#, click Windows Classic Desktop, and then click the
Windows Forms App template. Name the project CSWinApp .
3. With the project selected in Solution Explorer, on the Project menu, click Properties.
4. In the Project Designer, locate the Publish page and set Publishing location to C:\TEMP\ .
5. Publish the project by clicking Publish Now.
The manifest file will be built and put in C:\TEMP\CSWinApp_1_0_0_0\CSWinApp.exe.manifest . To view the
manifest, right-click the file, click Open with, select Select the program from a list, and then click
Notepad.
Search in the file for the <osVersionInfo> element. For example, the version might be:
6. In the Project Designer, click the Build Events tab and click the Edit Post-build button.
7. In the Post-build Event Command Line box, type the following command:
C:\TEMP\ChangeOSVersionCS.exe "$(TargetPath).manifest" 5.1.2600.0
When you build the project, this command will change the minimum operating system version in the
application manifest to 5.1.2600.0.
Because the $(TargetPath) macro expresses the full path for the executable being created, the
$(TargetPath) .manifest will specify the application manifest created in the bin directory. Publishing will
copy this manifest to the publishing location that you set earlier.
8. Publish the project again. Go to the Publish page and click Publish Now.
View the manifest again. To view the manifest, open the publish directory, right-click the file, click Open
with, select Select the program from a list, and then click Notepad.
The version should now read:
See Also
Build Events Page, Project Designer (C#)
Pre-build Event/Post-build Event Command Line Dialog Box
How to: Specify Build Events (Visual Basic)
Compiling and Building
Configuring Warnings in Visual Basic
10/18/2017 • 5 min to read • Edit Online
The Visual Basic compiler includes a set of warnings about code that may cause run-time errors. You can use that
information to write cleaner, faster, better code with fewer bugs. For example, the compiler will produce a warning
when the user attempts to invoke a member of an unassigned object variable, return from a function without
setting the return value, or execute a Try block with errors in the logic to catch exceptions.
Sometimes the compiler provides extra logic on the user's behalf so that the user can focus on the task at hand,
rather than on anticipating possible errors. In previous versions of Visual Basic, Option Strict was used to limit
the additional logic that the Visual Basic compiler provides. Configuring warnings allows you to limit this logic in a
more granular way, at the level of the individual warnings.
You may want to customize your project and turn off some warnings not pertinent to your application while
turning other warnings into errors. This page explains how to turn individual warnings on and off.
/warnaserror+:<warning list > Treat specific warnings as errors, listed by their error ID
number in a comma delimited list r.
/warnaserror-:<warning list> Do not treat specific warnings as errors, listed by their error ID
number in a comma delimited list.
Examples
This table of examples of command line arguments describes what each argument does.
ARGUMENT DESCRIPTION
vbc /warnaserror:42024,42025 Specifies that warnings 42024 and 42025 should be treated
as errors.
vbc /nowarn:42024,42025 Specifies that warnings 42024 and 42025 should not be
reported.
Types of Warnings
Following is a list of warnings that you might want to treat as errors.
Implicit Conversion Warning
Generated for instances of implicit conversion. They do not include implicit conversions from an intrinsic numeric
type to a string when using the & operator. Default for new projects is off.
ID: 42016
Late bound Method Invocation and Overload Resolution Warning
Generated for instances of late binding. Default for new projects is off.
ID: 42017
Operands of Type Object Warnings
Generated when operands of type Object occur that would create an error with Option Strict On . Default for
new projects is on.
ID: 42018 and 42019
Declarations Require 'As' Clause Warnings
Generated when a variable, function, or property declaration lacking an As clause would have created an error
with Option Strict On . Variables that do not have a type assigned to them are assumed to be type Object .
Default for new projects is on.
ID: 42020 (variable declaration), 42021 (function declaration), and 42022 (property declaration).
Possible Null Reference Exception Warnings
Generated when a variable is used before it has been assigned a value. Default for new projects is on.
ID: 42104, 42030
Unused Local Variable Warning
Generated when a local variable is declared but never referred to. Default is on.
ID: 42024
Access of Shared member through Instance Variable Warning
Generated when accessing a shared member through an instance may have side effects, or when accessing a
shared member through an instance variable is not the right-hand side of an expression or is being passed in as a
parameter. Default for new projects is on.
ID: 42025
Recursive Operator or Property Access Warnings
Generated when the body of a routine uses the same operator or property it is defined in. Default for new projects
is on.
ID: 42004 (operator), 42026 (property)
Function or Operator without Return Value Warning
Generated when the function or operator does not have a return value specified. This includes omitting a Set to
the implicit local variable with the same name as the function. Default for new projects is on.
ID: 42105 (function), 42016 (operator)
Overloads Modifier Used in a Module Warning
Generated when Overloads is used in a Module . Default for new projects is on.
ID: 42028
Duplicate or Overlapping Catch Blocks Warnings
Generated when a Catch block is never reached due to its relation to other Catch blocks that have been defined.
Default for new projects is on.
ID: 42029, 42031
See Also
Error Types
Try...Catch...Finally Statement
/nowarn
/warnaserror (Visual Basic)
Compile Page, Project Designer (Visual Basic)
Compiler Warnings That Are Off by Default
How to: Disable the Hosting Process
10/18/2017 • 1 min to read • Edit Online
Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable
the hosting process to return the correct results.
To disable the hosting process
1. Open an executable project in Visual Studio. Projects that do not produce executables (for example, class
library or service projects) do not have this option.
2. On the Project menu, click Properties.
3. Click the Debug tab.
4. Clear the Enable the Visual Studio hosting process check box.
When the hosting process is disabled, several debugging features are unavailable or experience decreased
performance. For more information, see Debugging and the Hosting Process.
In general, when the hosting process is disabled:
The time needed to begin debugging .NET Framework applications increases.
Design-time expression evaluation is unavailable.
Partial trust debugging is unavailable.
See Also
Debugging and the Hosting Process
Hosting Process (vshost.exe)
Builds During Application Development
Hosting Process (vshost.exe)
10/18/2017 • 1 min to read • Edit Online
The hosting process is a feature in Visual Studio that improves debugging performance, enables partial trust
debugging, and enables design time expression evaluation. The hosting process files contain vshost in the file
name and are placed in the output folder of your project. For more information, see Debugging and the Hosting
Process.
NOTE
Hosting process files (.vshost.exe) are for use by Visual Studio and should not be run directly or deployed with your
application.
See Also
Debugging and the Hosting Process
How to: Disable the Hosting Process
Immediate Window
Application Domains
Walkthrough: Creating a Multiple-Computer Build
Environment
10/18/2017 • 12 min to read • Edit Online
You can create a build environment within your organization by installing Visual Studio on a host computer and
then copying various files and settings to another computer so that it can participate in builds. You don't have to
install Visual Studio on the other computer.
This document does not confer rights to redistribute the software externally or to provide build environments to
third parties.
Disclaimer
This document is provided on a "as-is" basis. While we have tested the steps outlined, we are not able to
exhaustively test every configuration. We will attempt to keep the document current with any additional
information learned. Information and views expressed in this document, including URL and other Internet
website references, may change without notice. Microsoft makes no warranties, express or implied, with respect
to the information provided here. You bear the risk of using it.
This document does not provide you with any legal rights to any intellectual property in any Microsoft product.
You may copy and use this document for your internal, reference purposes.
You have no obligation to give Microsoft any suggestions, comments or other feedback ("Feedback") relating to
this document. However, any Feedback you voluntarily provide may be used in Microsoft Products and related
specifications or other documentation (collectively, "Microsoft Offerings") which in turn may be relied upon by
other third parties to develop their own products. Accordingly, if you do give Microsoft Feedback on any
version of this document or the Microsoft Offerings to which they apply, you agree: (a) Microsoft may freely
use, reproduce, license, distribute, and otherwise commercialize your Feedback in any Microsoft Offering; (b)
You also grant third parties, without charge, only those patent rights necessary to enable other products to use
or interface with any specific parts of a Microsoft Product that incorporate Your Feedback; and (c) You will not
give Microsoft any Feedback (i) that you have reason to believe is subject to any patent, copyright or other
intellectual property claim or right of any third party; or (ii) subject to license terms which seek to require any
Microsoft Offering incorporating or derived from such Feedback, or other Microsoft intellectual property, to be
licensed to or otherwise shared with any third party.
This walkthrough has been validated against the following operating systems, by executing MSBuild on the
command line and by using Team Foundation Build.
Windows 8 (x86 and x64)
Windows 7 Ultimate
Windows Server 2008 R2 Standard
After you complete the steps in this walkthrough, you can use the multiple-computer environment to build
these kinds of apps:
C++ desktop apps that use the Windows 8 SDK
Visual Basic or C# desktop apps that target the .NET Framework 4.5
The multiple-computer environment can't be used to build these kinds of apps:
Windows 8.x Store apps. To build Windows 8.x Store apps, you must install Visual Studio on the build
computer.
Desktop apps that target the .NET Framework 4 or earlier. To build these kinds of apps, you must install
either Visual Studio or the .NET Reference Assemblies and Tools (from the Windows 7.1 SDK) on the build
computer.
This walkthrough is divided into these parts:
Installing software on the computers
Copying files from the host computer to the build computer
Creating registry settings
Setting environment variables on the build computer
Installing MSBuild assemblies to the Global Assembly Cache (GAC) on the build computer
Building projects
Creating the build environment so that it can be checked into source control
Prerequisites
A licensed copy of Visual Studio Ultimate, Visual Studio Premium, or Visual Studio Professional
A copy of the .NET Framework 4.5.1, which you can download from the Visual Studio website.
NOTE
If the architecture of your host computer differs from that of your build computer, make sure to use the appropriate
parent key on each computer. This is especially important if you're automating the export process.
Also, if you're using a different drive letter on the build computer than the one that you're using on the host
computer, make sure to change the values of the registry entries to match.
2. Create the following registry entries on the build computer. All of these entries are strings (Type ==
"REG_SZ" in the registry). Set the values of these entries the same as the values of the comparable entries on
the host computer.
%RegistryRoot%\.NETFramework\v4.0.30319\AssemblyFoldersEx\VCMSBuild Public
Assemblies@(Default)
%RegistryRoot%\Microsoft SDKs\Windows\v8.0@InstallationFolder
%RegistryRoot%\Microsoft SDKs\Windows\v8.0A@InstallationFolder
%RegistryRoot%\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools@InstallationFolder
%RegistryRoot%\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x86@InstallationFolder
%RegistryRoot%\VisualStudio\11.0@Source Directories
%RegistryRoot%\VisualStudio\11.0\Setup\VC@ProductDir
%RegistryRoot%\VisualStudio\SxS\VC7@FrameworkDir32
%RegistryRoot%\VisualStudio\SxS\VC7@FrameworkDir64
%RegistryRoot%\VisualStudio\SxS\VC7@FrameworkVer32
%RegistryRoot%\VisualStudio\SxS\VC7@FrameworkVer64
%RegistryRoot%\VisualStudio\SxS\VC7@11.0
%RegistryRoot%\VisualStudio\SxS\VS7@11.0
%RegistryRoot%\Windows Kits\Installed Roots@KitsRoot
%RegistryRoot%\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath
%RegistryRoot%\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath10
%RegistryRoot%\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath11
On an x64 build computer, also create the following registry entry and refer to the host computer to
determine how to set it.
%RegistryRoot%\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x64@InstallationFolder
If your build computer is x64 and you want to use the 64-bit version of MSBuild, or if you're using
Team Foundation Server Build Service on an x64 computer, you must create the following registry
entries in the native 64-bit registry. Refer to the host computer to determine how to set these entries.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\11.0\Setup\VS@ProductDir
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath10
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0\11.0@VCTargetsPath11
If vcvarsall.bat runs successfully—that is, no error message is displayed—you can skip the next step and
continue at the Installing MSBuild assemblies to the Global Assembly Cache (GAC) on the build computer
section of this document.
To manually set environment variables
1. To manually configure the command-line environment, add this path to the PATH environment variable:
%Program Files%\Microsoft Visual Studio 11.0\Common7\IDE
2. Optionally, you can also add the following paths to the PATH variable to make it easier to use MSBuild to
build your solutions.
If you want to use the native 32-bit MSBuild, add these paths to the PATH variable:
%Program Files%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools
%windir%\Microsoft.NET\Framework\v4.0.30319
If you want to use the native 64-bit MSBuild, add these paths to the PATH variable:
%Program Files%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64
%windir%\Microsoft.NET\Framework64\v4.0.30319
NOTE
A reboot may be required for an assembly to fully install into the GAC.
Building projects
You can use Team Foundation Build to build Visual Studio 2012 projects and solutions, or you can build them on
the command line. When you use Team Foundation Build to build projects, it invokes the MSBuild executable that
corresponds to the system architecture. On the command line, you can use either 32-bit MSBuild or 64-bit MSBuild,
and you can choose the architecture of MSBuild by setting the PATH environment variable or by directly invoking
the architecture-specific MSBuild executable.
To use msbuild.exe at the command prompt, run the following command, in which solution.sln is a placeholder for
the name of your solution.
msbuild solution.sln
For more information about how to use MSBuild on the command line, see Command-Line Reference.
NOTE
To build Visual Studio 2012 projects, you must use the "v110" Platform Toolset. If you don't want to edit the Visual Studio
2012 project files, you can set the Platform Toolset by using this command-line argument:
msbuild solution.sln /p:PlatformToolset=v110
Creating the build environment so that it can be checked into source
control
You can create a build environment that can be deployed to various computers and doesn't require GAC'ing files or
modifying registry settings. The following steps are just one way to accomplish this. Adapt these steps to the
unique characteristics of your build environment.
NOTE
You must disable incremental building so that tracker.exe will not throw an error during a build. To disable incremental
building, set this build parameter:
msbuild solution.sln /p:TrackFileAccess=false
5. In each of your project files, add the following line at the top, after the <Project Default Targets...> line.
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),
Partner.AutoImports.props))\Partner.AutoImports.props"/>
See Also
Preparing a Test Machine To Run a Debug Executable
Command-Line Reference
Feature Tour of the Visual Studio Debugger
10/18/2017 • 8 min to read • Edit Online
This topic introduces the features of the Visual Studio debugger. If you want to follow along by opening your own
app in Visual Studio, you can do that, or you can follow along with a sample app using the Beginner's Guide.
The features described here are applicable to C#, C++, Visual Basic, JavaScript, and other languages supported by
Visual Studio (except where noted).
Press F5 (Debug > Start Debugging) and the debugger runs to the first breakpoint that it encounters. If the app
is not yet running, F5 starts the debugger and stops at the first breakpoint.
Breakpoints are a useful feature when you know the line of code or the section of code that you want to examine in
detail.
NOTE
In managed code, you will see a dialog box asking if you want to be notified when you automatically step over properties and
operators (default behavior). If you want to change the setting later, disable Step over properties and operators setting in
the Tools > Options menu under Debugging.
In this example, Step Into Specific gets us to the code for Path.set .
Run to a point in your code quickly using the mouse
While in the debugger, hover over a line of code until the Run to Click (Run execution to here) button appears
on the left.
NOTE
The Run to Click (Run execution to here) button is new in Visual Studio 2017.
Click the Run to Click (Run execution to here) button. The debugger advances to the line of code where you
clicked.
Using this button is similar to setting a temporary breakpoint. This command is also handy for getting around
quickly within a visible region of app code. You can use Run to Click in any open file.
Run to cursor
Stop the debugger by pressing the Stop Debugging red button or Shift + F5.
Right-click a line of code in your app and choose Run to Cursor. This command starts debugging and sets a
temporary breakpoint on the current line of code.
If you have set breakpoints, the debugger pauses on the first breakpoint that it hits.
Press F5 until you reach the line of code where you selected Run to Cursor.
This command is useful when you are editing code and want to quickly set a temporary breakpoint and start the
debugger.
NOTE
You can use Run to Cursor in the Call Stack window while you are debugging.
TIP
In most supported languages, you can edit code in the middle of a debugging session. For more info, see Edit and Continue.
In the Autos window, you see variables along with their current value and their type. The Autos window shows all
variables used on the current line or the preceding line (In C++, the window shows variables in the preceding three
lines of code. Check documentation for language-specific behavior).
NOTE
In JavaScript, the Locals window is supported but not the Autos window.
Next, look at the Locals window. The Locals window shows you the variables that are currently in scope.
In this example, the this object and the object f are in scope. For more info, see Inspect Variables in the Autos
and Locals Windows.
Set a watch
You can use a Watch window to specify a variable (or an expression) that you want to keep an eye on.
While debugging, right-click an object and choose Add Watch.
In this example, you have a watch set on the File object, and you can see its value change as you move through
the debugger. Unlike the other variable windows, the Watch windows always show the variables that you are
watching (they're grayed out when out of scope).
For more info, see Set a Watch using the Watch and QuickWatch Windows
The Call Stack window shows the order in which methods and functions are getting called. The top line shows the
current function (the Update method in this example). The second line shows that Update was called from the
Path.set property, and so on. The call stack is a good way to examine and understand the execution flow of an
app.
NOTE
The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.
You can double-click a line of code to go look at that source code and that also changes the current scope being
inspected by the debugger. This does not advance the debugger.
You can also use right-click menus from the Call Stack window to do other things. For example, you can insert
breakpoints into specific functions, restart your app using Run to Cursor, and to go examine source code. See How
to: Examine the Call Stack.
Examine an exception
When your app throws an exception, the debugger takes you to the line of code that threw the exception.
In this example, the Exception Helper shows you a System.Argument exception and an error message that says
that the path is not a legal form. So, we know the error occurred on a method or function argument.
In this example, the DirectoryInfo call gave the error on the empty string stored in the value variable.
The Exception Helper is a great feature that can help you debug errors. You can also do things like view error
details and add a watch from the Exception Helper. Or, if needed, you can change conditions for throwing the
particular exception.
NOTE
The Exception Helper replaces the Exception Assistant in Visual Studio 2017.
Expand the Exception Settings node to see more options on how to handle this exception type, but you don't
need to change anything for this tour!
See Also
Debugging in Visual Studio
Deploying Applications, Services, and Components
10/18/2017 • 1 min to read • Edit Online
By deploying an application, service, or component, you distribute it for installation on other computers, devices,
servers, or in the cloud. You choose the appropriate method in Visual Studio for the type of deployment that you
need.
The following table describes different deployment scenarios and provides links to more information for each
scenario.
For a discussion of options to create a setup experience for a Windows app, see Desktop to Universal Windows
Platform (UWP) Bridge.
In This Section
DEPLOYMENT SCENARIO SUPPORTING CONTENT
Publish to the cloud: You can make applications, services, Publishing Applications to Microsoft Azure
and data available from anywhere by using Visual Studio to
deploy them to Microsoft Azure.
Publish a Windows app: You can easily build, submit, and Publish Windows apps
sell your apps from the Windows Store to customers around
the world.
Deploy an ASP.NET application or service: You can deploy Deploying ASP.NET web applications and services
ASP.NET applications and services in a number of different
ways.
Publish an add-in for Office: You can publish an add-in for Deploy and publish your Office add-in
Office from Visual Studio.
Deploy a WCF or OData service: Other applications can use Developing and deploying WCF Data Services
WCF RIA services that you deploy to a web server.
Deploy a Visual C++ application: You can deploy the Visual Deploying Native Desktop Applications (Visual C++)
C++ runtime with an application by using central deployment,
local deployment, or static linking.
Deploy an application for testing: You can enable more Test on a lab environment
sophisticated development and testing by deploying your
applications into virtual environments.
DEPLOYMENT SCENARIO SUPPORTING CONTENT
Install prerequisites: You can install prerequisite components Application Deployment Prerequisites
for desktop applications by configuring a generic installer,
which is known as a bootstrapper.
Visual Studio provides a variety of profiling tools to help you diagnose different kinds of performance issues
depending on your app type.
The profiling tools that you can access during a debugging session are available in the Diagnostic Tools window.
The Diagnostic Tools window appears automatically unless you have turned it off. To bring up the window, click
Debug / Windows / Show Diagnostic Tools. With the window open, you can select tools for which you want to
collect data.
While you are debugging, you can use the Diagnostic Tools window to analyze CPU and memory usage, and you
can view events that show performance-related information.
The Diagnostic Tools window is often the preferred way to profile apps, but you can also do a post-mortem
analysis of your app instead. If you want more information on different approaches, see Running Profiling Tools
With or Without the Debugger.
To use the tool most effectively, set two breakpoints in your code, one at the beginning and one at the end of the
function or the region of code you want to analyze. Examine the profiling data when you are paused at the second
breakpoint.
The CPU Usage view shows you a list of functions ordered by longest running, with the longest running function at
the top. This can help guide you to functions where performance bottlenecks are happening.
Double-click on a function that you are interested in, and you will see a more detailed three-pane "butterfly" view,
with the selected function in the middle of the window, the calling function on the left, and called functions on the
right. The Function Body section shows the total amount of time (and the percentage of time) spent in the
function body excluding time spent in calling and called functions. This data can help you evaluate whether the
function itself is a performance bottleneck.
If you click the link on the left instead in the Memory Usage view, the heap view is organized by object count; the
objects of a particular type that increased the most in number are shown at the top (sorted by Count Diff column).
The same events also show up in the code editor, which you can view as PerfTips.
To diagnose UI responsiveness, slow loading time, and slow visual updates in Windows Universal HTML apps, use
the HTML UI Responsiveness tool. Usage is similar to the Application Timeline tool for other app types. For more
information, see HTML UI responsiveness.
IntelliTrace .NET Enterprise only .NET Enterprise only .NET Enterprise only
See Also
Debugging in Visual Studio
Finding and Using Visual Studio Extensions
10/18/2017 • 6 min to read • Edit Online
Visual Studio extensions are code packages that run inside Visual Studio and provide new or improved Visual
Studio features. You can find more information about Visual Studio extensions here: Visual Studio SDK.
You can use the Extensions and Updates dialog box to install Visual Studio extensions and samples from
websites and other locations, and then enable, disable, update, or uninstall them. (Tools / Extensions and
Updates, or type Extensions in the Quick Launch window). The dialog box also shows updates for installed
samples and extensions. You can also download extensions from websites, or get them from other developers.
NOTE
Starting in Visual Studio 2015, extensions hosted on the Visual Studio Gallery will be automatically updated. You can change
this setting through the Extensions and Updates dialog. See the section on Automatic Extension Updates below for
details.
NOTE
Starting in Visual Studio 2015 Update 2, you can specify (in Tools / Options / Environment / Extensions and Updates)
whether you want automatic updates for per-user extensions, all user extensions or both (the default setting).
TIP
If an MSI-based extension includes an extension.vsixmanifest file, the extension will appear in the Extensions and Updates
dialog box.
Improve Code Quality
10/18/2017 • 3 min to read • Edit Online
What is code quality? Correctness, maintainability, and even elegance are all involved in creating great code.
However you define it, Visual Studio test tools can help you and your team to develop and sustain high standards
of code excellence.
Requirements
Some of the tools and features that are described in this section are available only in specific editions of Visual
Studio—they aren't universally available in Visual Studio. We list the specific edition requirements in the
documentation for these tools and features.
In this section
In the following table, you can find descriptions of common tasks and links to more information about how you
can successfully complete those tasks.
Unit Test Your Code Test Explorer makes it easy to integrate unit tests in your
development practice. You can use the Microsoft unit test
framework or one of several third-party and open source
frameworks.
Live Unit Testing with Visual Studio Live Unit Testing automatically runs unit tests in the
background and graphically displays code coverage and test
results in the Visual Studio code editor.
Analyzing Application Quality Static code analysis tools find design, usage, maintainablity,
and style issues in C++ and managed code. Many of these
issues can lead to bugs that are hard to reproduce in standard
testing environment.
Measuring Complexity and Maintainability of Managed Code Code metrics is a set of software measures that provide
developers better insight into the code they are developing.
The metrics include a maintainability index for functions and
classes, cyclomatic complexity of functions, the inheritance
depth of classes, and the amount of coupling among classes.
Related Scenarios
DevOps overview for Team Services and TFS
If you are unfamiliar with Visual Studio Team Foundation and Visual Studio Team Services, you can learn more
about how you can use it in a team development environment to improve productivity and reduce risks that are
associated with application development.
Analyzing and Modeling Architecture
You can use Microsoft Visual Studio Premium to manage the challenges and complexity of designing software.
Visual Studio Premium lets you visually model your application, both as it exists now and as you want it to exist in
the future. You can create and maintain diagrams to help you visualize the logical models of your application at the
same time that they map to the physical models; this enables you to change, validate, and analyze the software that
is "under design."
Testing the application
You can use Visual Studio Premium and Visual Studio Ultimate to be more productive throughout the testing life
cycle. Visual Studio Premium or Visual Studio Ultimate let you plan your testing effort. You can create, manage,
edit, and run both manual and automated tests. You can also review your testing progress based on your plan.
Protecting the application with PreEmptive Protection - Dotfuscator
You can use the free Dotfuscator Community Edition to help secure trade secrets and other intellectual property
(IP), reduce piracy and counterfeiting, and protect against tampering and unauthorized debugging. Dotfuscator
protects and hardens compiled assemblies without the need for additional programming or even access to source
code.
Building the application
You can use Team Foundation Build to create and manage automated builds for your code. Team Foundation Build
lets you create drop servers to deploy builds. In addition, you can analyze build trends.
Tracking work using Visual Studio Online or Team Foundation Server
You can use Visual Studio Team Foundation Server to plan and track your projects whether you use the agile
process, the formal process, or a variation on those processes. By planning your projects, tracking your progress
against the plan, and making necessary adjustments, you can reduce risks, avoid unpleasant surprises, and manage
the cost of your projects.
Designing User Interfaces
10/18/2017 • 1 min to read • Edit Online
You can create and design the user interface for your application by using a variety of tools in Visual Studio.
The features of the XAML designers in Visual Studio and Blend Designing XAML in Visual Studio and Blend for Visual Studio
for Visual Studio
Designing any XAML-based app using Visual Studio Creating a UI by using XAML Designer in Visual Studio
Designing any XAML-based app using Blend for Visual Studio Creating a UI by using Blend for Visual Studio
Designing desktop applications that use the WPF flavor of Create Modern Desktop Applications with Windows
XAML Presentation Foundation
Developing a DirectX application in Visual Studio Working with 3-D Assets for Games and Apps
Standard icons available for your programs The Visual Studio Image Library
Analyze and model your architecture
10/18/2017 • 3 min to read • Edit Online
Make sure your app meets architectural requirements by using Visual Studio architecture and modeling tools to
design and model your app.
Understand existing program code more easily by using Visual Studio to visualize the code's structure,
behavior, and relationships.
Educate your team in the need for respecting architectural dependencies.
Create models at different levels of detail throughout the application lifecycle as part of your development
process.
See Scenario: Change your design using visualization and modeling.
To
Define the architecture: - Video: Validate architecture dependencies with Visual Studio
(Channel 9)
- Define and enforce constraints on dependencies between the
components of your code by creating dependency diagrams.
Validate your system with the requirements and intended - Video: Validate architecture dependencies with Visual Studio
design: (Channel 9)
Share models, diagrams, and code maps using Team When you have multiple users who work with these items
Foundation version control: under Team Foundation version control, use these guidelines
to help you avoid version control issues:
- Put code maps, projects, and deoendency diagrams under
Team Foundation version control so you can share them. - Manage models and diagrams under version control
Customize models and diagrams: - Modeling SDK for Visual Studio - Domain-Specific Languages
To see which versions of Visual Studio support each feature, see Version support for architecture and modeling
tools
Code maps
Code maps help you see the organization and relationships in your code.
Typical uses:
- Examine program code so you can better understand its structure and its dependencies, how to update it, and estimate the cost
of proposed changes.
See:
Dependency diagram
Dependency diagrams let you define the structure of an application as a set of layers or blocks with explicit dependencies. You can
run validation to discover conflicts between dependencies in the code and dependencies described on a dependency diagram.
Typical uses:
- Stabilize the structure of the application through numerous changes over its life.
- Discover unintentional dependency conflicts before checking in changes to the code.
See:
A DSL is a notation that you design for a specific purpose. In Visual Studio, it is usually graphical.
Typical uses:
- Generate or configure parts of the application. Work is required to develop the notation and tools. The result can be a better fit
to your domain than a UML customization.
- For large projects or in product lines where the investment in developing the DSL and its tools is returned by its use in more
than one project.
See:
See Also
What's new
DevOps and Application Lifecycle Management
Visual Studio IDE 64-Bit Support
10/18/2017 • 1 min to read • Edit Online
Visual Studio enables you to set up your applications to target different platforms, including 64-bit platforms. For
more information on 64-bit platform support in Visual Studio, see 64-bit Applications.
See Also
How to: Configure Projects to Target Platforms
Security in Visual Studio
10/18/2017 • 1 min to read • Edit Online
You should consider security in all aspects of your application development, from design to deployment. Start by
running Visual Studio as securely as possible. See User Permissions.
To help you effectively develop secure applications, you should have a fundamental understanding of security
concepts and the security features of the platforms for which you develop. You should also understand secure
coding techniques.
Understanding Security
Security
Describes .NET Framework code access security, role-based security, security policy, and security tools.
Defend Your Code with Top Ten Security Tips Every Developer Must Know
Describes the issues that you should watch out for so that you don't compromise your data or your system.
While most applications possess common security challenges, each application domain possesses security
challenges of its own.
It is often said that the price of security is constant vigilance. Despite your best dedication to security during the
design and development of your application, you should assume that security flaws will arise after deployment. By
auditing your application and analyzing event logs, you may discover some previously hidden flaws.
In addition, not only must you remain vigilant about your own application, you must also keep current on security
threats and flaws for the platform on which your application runs and for other products on which your application
depends.
Security, Privacy, and Accounts
Get help with security, privacy, and user accounts, including info about viruses, passwords, parental controls,
firewalls, and drive encryption..
Microsoft Security Bulletin Search
This page makes it easy to find previously released bulletins. Intended for IT professionals, security bulletins
provide detailed information regarding security updates.
Windows Server 2003 Security Guide
Delivers the guidance necessary for IT Professionals to securely operate a Windows Server 2003 environment while
ensuring the right access to the right content by the right people.
Best Practices for Enterprise Security
A collection of whitepapers focusing on the different aspects of security in enterprise networks.
Microsoft Baseline Security Analyzer
The Microsoft Baseline Security Analyzer (MBSA) is a tool that enables an individual home user, a corporate user, or
an administrator to scan one or more Windows-based computers for common security configuration mistakes.
User Permissions and Visual Studio
10/18/2017 • 2 min to read • Edit Online
For reasons of security you should run Visual Studio as a normal user whenever possible.
WARNING
You should also make sure not to compile, launch, or debug any Visual Studio solution that does not come from a trusted
person or a trusted location.
You can do nearly everything in the Visual Studio IDE as a normal user, but, you need administrator permissions to
complete the following tasks:
Add-ins Installing and using add-ins that were Creating Add-ins and Wizards
written by using classic COM in the IDE.
Building Using post-build events that register a Understanding Custom Build Steps and
component. Build Events
Including a registration step when you Understanding Custom Build Steps and
build C++ projects. Build Events
Debugging Debugging applications that run with Debugger Settings and Preparation
elevated permissions.
See Also
Porting, Migrating, and Upgrading Visual Studio Projects
Install Visual Studio
Security Bibliography
10/18/2017 • 1 min to read • Edit Online
Following are selected resources available online and in print on the subject of developing secure applications and
configuring secure environments:
You can find Visual Studio samples on the MSDN Code Gallery website.
Finding Samples
Here are some other places to look for samples.
AREA DESCRIPTION
Windows Developer Center Samples Shows how to develop Windows 8.x Store apps.
.NET Framework Samples Shows various aspects of the .NET Framework in C# and
Visual Basic.
Visual Basic Samples Shows how to use different features of Visual Basic.
Office Development Samples Shows how to use Office development tools in Visual Studio.
For the most current samples, see MSDN Developer Samples:
Learn Through Code.
See Also
Getting Started with Visual C# and Visual Basic
Microsoft Help Viewer
10/18/2017 • 3 min to read • Edit Online
You can install and view content for various products and technologies on your local computer by using Microsoft
Help Viewer.
WARNING
When you install Visual Studio, you have the option of installing the Help Viewer. To start reading help topics in the Help
Viewer rather than on the MSDN download site, after installing the Help Viewer, go to the Help menu in Visual Studio,
choose Set Help Preference, and then choose Launch in Help Viewer. The off-line help topics for a given version of Visual
Studio are available only after the final release of that version.
Navigation By using the Contents tab, you can display installed content
as a hierarchy and specify criteria to filter the titles that
appear.
By using the Search tab, you can search for terms anywhere
in the content, including code and topic titles.
By using the Index tab, you can search the index, specify
criteria to filter the entries, and require that index entries
either contain or start with text that you specify.
By using the Favorites tab, you can save links to topics that
you use frequently, and you can display a list of topics that
you've viewed recently.
Topic viewing Each topic appears in a tab, and you can open multiple topics
at the same time.
Managing content You can install, update, move, and delete content by using the
Manage Content tab. At the top of the tab, you can use the
Installation source control to specify whether to install books
from a network location or from a disk or URI. The Local
store path box shows where books are installed on the local
computer, and you can move them to a different location by
choosing the Move button.
The content list shows which books you can install or have
already installed, whether an update is available, and how
large each book is. You can install or remove one or more
books by choosing the appropriate Add or Remove links and
then choosing the Update button under the Pending
changes pane. If updates are available for any books that
you've already installed, you can refresh that content by
choosing the Click here to download now link at the
bottom of the window. In addition, all installed books will be
refreshed if updates are available when you install additional
books. Note: The functionality of the Manage Content tab
may differ if the Help Viewer administrator deactivates these
features, or if no internet access is available.
The toolbar in the Help Viewer window contains the following buttons:
The Show Topic in Contents button shows the location of the topic in the Contents tab.
The Add to Favorites button adds the active topic to the Favorites tab.
The Find in Topic button highlights search text in the active topic.
The Print button prints or shows a preview of the active topic.
The Viewer Options button displays settings such as how large the text appears, how many search results
to return, how many topics to show in history, and whether to check for updates online.
The Manage Content button makes the Manage Content tab active.
The small triangle opens a list of tabs, including topic tabs and the Manage Content tab. You can make any
of those tabs active by choosing it.
The lower area of the Help Viewer window contains information about the total size of pending downloads,
the amount of disk space that they require, and the amount of disk space that's available. This area also
contains information about errors that may have occurred and a link that you can choose to refresh installed
content, if updates are available.
See Also
Help Viewer Administrator Guide
Install and Manage Local Content
Locate Information
Troubleshooting the Help Viewer
Microsoft Help Viewer Installation
10/18/2017 • 1 min to read • Edit Online
Several products display Help in Microsoft Help Viewer. Installation instructions will vary based on which product
installed the Help Viewer.
The Help Viewer allows you to manage local Help installations for network environments with or without internet
access. Local help content is configured on a per machine basis. By default, users must have administrator rights to
update their local Help installation.
If your network environment allows clients to access the internet, the Help Viewer allows you to use command line
scripts to deploy local Help content from the internet.
If your network environment does not allow clients to access the internet, the Help Viewer can deploy local Help
content from the intranet or a network share. You can also disable Visual Studio IDE Help options, such as
online/offline help, content installation at first launch of the IDE, specifying an intranet content service, and
managing content, using registry key overrides.
The basic syntax is as follows:
<path to>\HlpCtntmgr.exe /operation <argument> /catalogname <name> /locale <locale> /sourceuri <.msha
path or URL>
For more information about HlpCtntMgr.exe command line syntax, see Command-Line Arguments for the Help
Content Manager.
For more information about creating content, creating an intranet service endpoint, and similar types of activities,
see the Help Viewer SDK.
TIP
You can change the default source for Help by modifying the
HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\14.0\help\UseOnlineHelp registry key. For more
information, see Help Content Manager Overrides.
Clients will still be prompted to install the basic Help content on the first launch of Visual Studio. You can
disable this prompt by modifying the
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\Help\DisableFirstRunHe
lpSelection registry key.
Example
The following example installs English content for Visual Studio to a client computer.
To i n st a l l En g l i sh c o n t e n t fr o m t h e I n t e r n e t
TIP
If users do not have administrator rights, it is recommended that you disable the Manage Content tab in the Help
Viewer. For more information, see Help Content Manager Overrides.
Caveats:
If users do not have administrator rights, it is recommended that you disable the Manage Content tab in the
Help Viewer. For more information, see Help Content Manager Overrides.
The default source for Help will still be Online.
Clients will still be prompted to install the basic Help content on the first launch of Visual Studio. For more
information, see Help Content Manager Overrides.
Create the content set
Before you can create the base content set, you must first uninstall all local Visual Studio content on the target
computer.
To u n i n st a l l l o c a l h e l p
1. Create a network share and copy theee help content to that location.
For example, copy the content in c:\VS12Help to \\myserver\VS12Help.
2. Create a .bat file to contain the deployment script for the help content. Since the client could possibly have a
read lock on any of the files being deleted as part of the push, you should have the client shut down prior to
pushing updates.
For example:
REM - copy pre-ripped content to ProgramData
Xcopy %~dp0HelpLibrary2 %SYSTEMDRIVE%\ProgramData\Microsoft\HelpLibrary2\ /y /e /k /o
if ERRORLEVEL 1 ECHO *** ERROR COPYING Help Library files to Programdata (%ERRORLEVEL%)
regedit.exe /s x86.reg
if ERRORLEVEL 1 ECHO *** ERROR inserting the x86 reg (%ERRORLEVEL%)
GOTO CONTINUE
:AMD64
@echo Architecture type is AMD64
regedit.exe /s x64.reg
if ERRORLEVEL 1 ECHO *** ERROR inserting the x64 reg (%ERRORLEVEL%)
:CONTINUE
3. Run the bat file on the local machines that the Help content is to be installed onto.
See Also
Command-Line Arguments for the Help Content Manager
Help Content Manager Overrides
Command-Line Arguments for the Help Content
Manager
10/18/2017 • 5 min to read • Edit Online
You can specify how to deploy and manage local Help content by using command-line arguments for Help
Content Manager (HlpCtntmgr.exe). You must run scripts for this command-line tool with administrator
permissions, and you can't run these scripts as a service. You can perform the following tasks by using this tool:
Add or update local Help content from a disk or the cloud.
Remove local Help content.
Move the local Help content store.
Add, update, remove, or move local Help content silently.
Syntax:
For example:
Exit Codes
When you run the command-line tool for the Help Content Manager in silent mode, it returns the following exit
codes:
Success = 0,
FailureToElevate = 100
InvalidCmdArgs = 101,
FailOnFetchingOnlineContent = 110,
FailOnFetchingContentFromDisk = 120,
FailOnFetchingInstalledBooks = 130,
NoBooksToUninstall = 200,
NoBooksToInstall = 300,
FailOnUninstall = 400,
FailOnInstall = 500,
FailOnMove = 600,
FailOnUpdate = 700,
FailOnRefresh = 800,
Cancelled = 900,
Others = 999,
ContentManagementDisabled = 1200,
OnlineHelpPreferenceDisabled = 1201
UpdateAlreadyRunning = 1300 - (Signals that the update didn't run because another was in progress.)
See Also
Help Viewer Administrator Guide
Help Content Manager Overrides
Help Content Manager Overrides
10/18/2017 • 1 min to read • Edit Online
You can modify the registry to change the default behavior of the Help Viewer and Help-related features in the
Visual Studio IDE.
See Also
Help Viewer Administrator Guide
Install and Manage Local Content
10/18/2017 • 3 min to read • Edit Online
By using the Microsoft Help Viewer, you can add, remove, update, and move the Help content that is installed on
your computer to fit your software-development needs.
To manage content on your local computer, you must log on with an account that has administrative permissions.
In addition, you might not be able to manage local content if you work in an enterprise environment because
system administrators might make those decisions for your organization. For more information, see the Help
Viewer Administrator Guide.
NOTE
The Disk option won't be available if your administrator has prevented you from modifying the content installation
source. For more information, see the Help Viewer Administrator Guide.
IMPORTANT
To install content, you must log on with an account that has administrative permissions.
If the Visual Studio IDE is set to a language other than English, you can install English content, localized content, or
both. However, no content will appear if you install only the English version and the Include English content in
all navigation tabs and F1 requests check box in the Viewer Options dialog box is cleared.
To download and install content
1. Choose the Manage Content tab.
2. In the content list, choose the Add link next to the book or books that you want to download and install.
The book is added to the Pending changes list, and the estimated size of the book or books that you
specified appears below that list. Because some books share topics, the total download size of multiple
books might be smaller than the result of adding together the sizes of every book that you specified.
3. Choose the Update button.
The book or books that you specified are installed along with any updates for books that you already have
on your computer. Installation times vary, but you can view the progress in the status bar.
IMPORTANT
You must have administrative permissions to remove content.
No content will appear if the Visual Studio IDE is set to a language other than English, you remove localized
content, and the Include English content in all navigation tab and F1 requests check box in the Viewer
Options dialog box is cleared.
To remove content
1. Choose the Manage Content tab.
2. In the content list, choose the Remove link next to the book or books that you want to remove.
The book is added to the Pending changes list.
3. Choose the Update button.
The book or books that you specified are removed from your computer.
IMPORTANT
If you want the Help Viewer to automatically check for online updates, you must open the Viewer Options dialog box and
then select the Go online to check for content updates check box.
IMPORTANT
To move content, you must log on with an account that has administrative permissions.
See Also
Microsoft Help Viewer
Locate Information
10/18/2017 • 1 min to read • Edit Online
The Help Viewer provides several different ways for you to locate information in Help. Depending on what kind of
information you're looking for, certain strategies might be more effective than others.
Other topics that are in the same area of the table of contents The Show Topic in Contents button on the toolbar
as the current topic
In this Section
Full-Text Search Tips
How to: Find Topics in the Table of Contents
How to: Find Topics in the Index
10/18/2017 • 1 min to read • Edit Online
The index contains a list of keywords that are associated with topics in the installed content. Each topic might have
more than one keyword associated with it, and each keyword might be associated with more than one topic. Use
this index in the same way as you would use an index in a book.
To find a topic by using the index
1. On the Index tab, perform either of the following tasks:
Specify the keyword to search for in the text box. For example, specify "update" to find topics with
keywords such as "update," "updated," and "updating."
By choosing the filter button near the top of the tab, you can display either all entries that contain the
text that you specify or only those entries that start with the text that you specify.
NOTE
When the filter button appears on a darker background with a border, entries must contain the text that you
specify. If the background and border don't appear, entries must start with the text that you specify.
See Also
Index Search Tips
Index Search Tips
10/18/2017 • 1 min to read • Edit Online
You can locate information in the Index by entering keywords. This topic suggests useful ways to search Help using
the Index.
See Also
Full-Text Search Tips
Locate Information
How to: Find Topics in the Table of Contents
10/18/2017 • 1 min to read • Edit Online
In the Contents tab, you can use the table of contents (TOC) to find information. The table of contents is an
expandable list that contains all of the topics in the installed books. For accessibility information about how to
navigate through the TOC, see Shortcut Keys (Help Viewer).
IMPORTANT
The scope of topics available in the TOC depends on the filter you have selected.
NOTE
If the filter takes a long time to run, you might display results more quickly by using the title: advanced search operator.
See Also
Locate Information
Microsoft Help Viewer
How to: Search for Topics
10/18/2017 • 1 min to read • Edit Online
You can use the full-text search feature to locate all topics that contain a particular word. You can also refine and
customize your search by using wildcard expressions, logical operators, and advanced search operators.
To open the Search tab
Choose the Search tab in the Help Viewer window, or choose the Ctrl + E keys.
To perform a full-text search
1. In the search box, type the word that you want to find.
2. In the search query, specify which logical or advanced search operators to apply to the search, if any. To
search all available Help, don't use operators.
NOTE
In the Viewer Options dialog box, you can specify additional preferences such as the maximum number of search
results to display at a time and whether to include English content if your primary locale is not English.
See Also
Full-Text Search Tips
Logical Operators in Search Expressions
Advanced Search Operators in Search Expressions
How to: Customize Search Results
Full-Text Search Tips
10/18/2017 • 2 min to read • Edit Online
One of the more useful methods of locating information in Help is by performing a full-text search. To refine and
customize your results, you must understand how syntax affects your query. This topic provides tips, procedures,
and detailed syntax information to help you better craft your queries.
SYNTAX DESCRIPTION
Character combinations You can't search only for individual letters (a-z) or numbers
(0-9). If you try to search for certain reserved words, such as
"and", "from", and "with", they will be ignored. For more
information, see "Words Ignored in Searches (Stop Words)"
later in this topic.
Search Syntax
If you specify a search string that includes multiple words, such as "word1 word2," that string is equivalent to
typing "word1 AND word2", which returns only topics that contain all of the individual words in the search string.
IMPORTANT
1. Phrase searches are not supported. If you specify more than one word in a search string, returned topics will contain all
of the words that you specified but not necessarily the exact phrase that you specified.
a. Use logical operators to specify the relationship between words in your search phrase. You can include logical
operators, such as AND, OR, NOT, and NEAR, to further refine your search. For example, if you search for
"declaring NEAR union", search results will include topics that contain the words "declaring" and "union" no more
than a few words apart from each other. For more information, see Logical Operators in Search Expressions.
Filters
You can further restrict search results by using advanced search operators. Help includes three categories that you
can use to filter results of a full-text search: Title, Code, and Keyword. For more information, see Advanced Search
Operators in Search Expressions.
Ranking of Search Results
The search algorithm applies certain criteria to help rank search results higher or lower in the results list. In
general:
1. Content that includes search words in the title is ranked higher than content that doesn't.
2. Content that includes search words in close proximity is ranked higher than content that doesn't.
3. Content that contains a higher density of the search words is ranked higher than content that has a lower
density of the search words.
Words Ignored in Searches (Stop Words)
Commonly occurring words or numbers, which are sometimes called stop words, are automatically ignored
during a full-text search. For example, if you search for the phrase "pass through", search results will display topics
that contain the word "pass" but not "through".
See Also
Locate Information
Logical Operators in Search Expressions
Logical Operators in Search Expressions
10/18/2017 • 1 min to read • Edit Online
By using logical operators, you can refine your search for content by creating more complicated search
expressions from simpler ones. As the following table shows, logical operators specify how multiple search terms
should be combined in a search query.
IMPORTANT
You must enter logical operators in all capital letters for the search engine to recognize them.
Both terms in the same AND dib AND palette Topics that contain both
topic "dib" and "palette".
First term without the NOT "operating system" NOT Topics that contain
second term in the same DOS "operating system" but not
topic "DOS".
Both terms, close together NEAR user NEAR kernel Topics that contain "user"
in a topic within close proximity of
"kernel".
See Also
Full-Text Search Tips
Locate Information
Advanced Search Operators in Search Expressions
10/18/2017 • 1 min to read • Edit Online
By using advanced search operators in the Help Viewer, you can refine your search for content by creating more
complicated search expressions from simpler ones. As the following table shows, these operators restrict the
context in which a query runs.
WARNING
You must enter advanced search operators with a final colon and no intervening space before the colon for the search engine
to recognize them.
You can use the code: operator to find content about any of several programming languages, but it returns results
only for content that is marked up with a specific programming language. The following table lists the
programming languages that this operator supports:
or
code:visualbasic
C# code:c#
or
code:csharp
PROGRAMMING LANGUAGE USE
C++ code:cpp
or
code:c++
or
code:cplusplus
F# code:f#
or
code:fsharp
JavaScript code:javascript
or
code:js
XAML code:xaml
See Also
Logical Operators in Search Expressions
Full-Text Search Tips
How to: Customize Search Results
10/18/2017 • 1 min to read • Edit Online
You can customize how search results appear in the Search tab in several ways.
WARNING
This feature is enabled only if the primary language of installed content isn't English.
See Also
Full-Text Search Tips
Manage the Help Viewer Window
10/18/2017 • 1 min to read • Edit Online
Docking Tabs
The Help Viewer supports standard docking functionality. By default, all tabs in the Help Viewer are docked, but you
can move them, resize them, dock them in other locations, and "float" them so that they appear as independent
child windows.
To restore the Help Viewer window to its default layout, open the Viewer Options dialog box, and then choose the
Reset button.
When you locate a useful topic, you can access it later by copying it and pasting it into a text file, printing it, or
saving it as a favorite. For example, you can retain content for later use by opening the shortcut menu for topics
and the choosing the Copy, Print, Print Preview, and Add to Favorites options.
See Also
Shortcut Keys (Help Viewer)
Customize the Help Viewer
10/18/2017 • 1 min to read • Edit Online
You can configure several features of the Help Viewer by using the Viewer Options dialog box.
Change the size of the font in which text appears Choose a size in the Text Size list.
Change the maximum number of search results that appear in Choose a value in the Maximum Search Results list.
the Search tab
Change the maximum number of history entries that appear Choose a value in the Maximum History entries saved list.
in the Favorites window
Include or exclude English content when you view content for Select or clear the Include English content in all navigation
a non-English version of a product. tabs and F1 requests check box. Caution: This feature also
controls whether you can download English content in the
Manage Content tab.
Troubleshooting the Help Viewer
10/18/2017 • 1 min to read • Edit Online
This topic discusses issues that you might encounter with the Help Viewer.
Additional Resources
You can get more information and provide feedback on the Help Viewer by using the following resources:
To provide feedback, see Microsoft Connect on the Microsoft website or send email to
hlpfdbk@microsoft.com.
For more information, see the Developer Documentation and Help System forum and The Help Guy blog.
See Also
Help Viewer 2.1 Administrator Guide
Accessibility Features of the Help Viewer
10/18/2017 • 1 min to read • Edit Online
Microsoft is committed to making its products and services easier for everyone to use. This topic includes
information about the features, products, and services that help make Microsoft Help Viewer 2.2 accessible for
people with a wide range of abilities.
Keyboard access
You can access all features of the Help Viewer by using the keyboard. For more information, see Shortcut Keys
(Help Viewer).
Font size
You can modify the font size in which topic text appears in the document window. For more information, see
Customize the Help Viewer.
Window size
You can change the width of the navigation or document windows by pointing to the divider between the two
windows. When the cursor changes to a double-headed arrow, use the primary mouse button to drag the divider to
the right or left.
See Also
Microsoft Help Viewer
Shortcut Keys (Help Viewer)
10/18/2017 • 5 min to read • Edit Online
You can navigate in the Microsoft Help Viewer by using the shortcut keys in the following table:
-OR-
-OR-
Ctrl + Shift + C
AREA KEYSTROKE ACTION
-OR-
Ctrl + Shift + I
-OR-
Ctrl + Shift + F
-OR-
Ctrl + E
-OR-
Ctrl + Shift + S
-OR-
Ctrl + Shift + M
Topic Shortcut Menu key Display the shortcut menu for the
current UI element.
OR
Shift + F10
Topic Ctrl + Shift + Tab Switch among tabs from right to left.
Contents & Index & Search Ctrl + D Add the specified topic to the
Favorites tab.
Contents & Index & Search & Favorites Ctrl + P Print the specified topic.
AREA KEYSTROKE ACTION
Contents & Index & Search & Favorites Ctrl + F2 Display a print preview of the specified
topic.
Contents & Index & Search & Favorites Ctrl + Click Open the topic in a new tab.
Status bar Alt + E Open the Error dialog box if the status
bar shows that an error has occurred.
Window Management
Keystroke Action
Ctrl + L Reset the Help Viewer layout to the default layout, and close
all topic tabs.
Ctrl + Tab The first keystroke gives focus to the Tab Selection menu.
The next keystroke gives focus to the top menu item, and
subsequent keystrokes give focus to the menu items in
sequence from top to bottom. When a menu item has focus,
the Enter key makes that item the active tab.
Ctrl + Shift + Tab The first keystroke gives focus to the Tab Selection menu.
The next keystroke gives focus to the bottom menu item, and
subsequent keystrokes give focus to the menu items in
sequence from bottom to top. When a menu item has focus,
the Enter key makes that item the active tab.
Alt + I, Alt + S, Alt + C, Alt + F, Alt + M These shortcut keys don't work when the navigation and
content-management tabs are undocked.
Manage Content
Keystroke Action
Up Arrow and Down Arrow Scroll through the Pending changes list.
PreEmptive Protection - Dotfuscator provides comprehensive .NET application protection that easily fits into your
secure software development lifecycle. Use it to harden, protect, and prune desktop, mobile, server, and embedded
applications to help secure trade secrets and other intellectual property (IP), reduce piracy and counterfeiting, and
protect against tampering and unauthorized debugging. Dotfuscator works on compiled assemblies without the
need for additional programming or even access to source code.
About Dotfuscator CE
Your copy of Microsoft Visual Studio 2017 includes a copy of PreEmptive Protection - Dotfuscator Community
Edition, also known as Dotfuscator CE, free for personal use. For instructions on how to install the version of
Dotfuscator CE included with Visual Studio 2017, see the Installation page.
Dotfuscator CE offers a range of software protection and hardening services for developers, architects and testers.
Examples of .NET Obfuscation and other Application Protection features included in Dotfuscator CE are:
Renaming of identifiers to make reverse-engineering of the compiled assemblies more difficult.
Anti-tamper to detect the execution of tampered applications, transmit incident alerts, and terminate tampered
sessions.
Anti-debug to detect the attachment of a debugger to a running application, transmit incident alerts, and
terminate debugged sessions.
Application expiration behaviors that encode an "end-of-life" date, transmit alerts when applications are
executed after their expiration date, and terminate expired application sessions.
Exception tracking to monitor unhandled exceptions occurring within the application.
Session and feature usage tracking to determine what applications have been executed, what versions of those
applications, and what features are used in those applications.
For details on these features, including how they fit into your application protection strategy, see the Capabilities
page.
Dotfuscator CE offers basic protection out-of-the-box. Even more application protection measures are available to
registered users of Dotfuscator CE, and to users of PreEmptive Protection - Dotfuscator Professional Edition, the
world's leading .NET Obfuscator. For information about enhancing Dotfuscator, see the Upgrades page.
Getting Started
To begin using Dotfuscator CE from Visual Studio, type dotfuscator into the Quick Launch (Ctrl+Q) search bar.
If Dotfuscator CE is already installed, this will bring up the Menu option to start the Dotfuscator CE user
interface. For details, see the Getting Started page of the full Dotfuscator CE User Guide.
If Dotfuscator CE is not yet installed, this will bring up the relevant Install option. See the Installation page for
details.
You can also get the latest version of Dotfuscator CE from the Dotfuscator Downloads page on preemptive.com.
Full Documentation
This page and its sub-pages provide a high-level overview of Dotfuscator CE's features, as well as instructions for
installing the tool.
Please see the full Dotfuscator CE User Guide at preemptive.com for detailed usage instructions, including how to
start using the Dotfuscator CE user interface.
Capabilities of Dotfuscator
10/19/2017 • 2 min to read • Edit Online
This page focuses on the capabilities of Dotfuscator Community Edition (Dotfuscator CE) with some references to
advanced options available through upgrades.
Dotfuscator is a post-build system for .NET applications. With Dotfuscator CE, Visual Studio users are able to
obfuscate assemblies and inject active defense and analytics tracking into the application - all without Dotfuscator
needing to access the original source code. Dotfuscator protects your application in multiple ways, creating a
layered protection strategy.
Dotfuscator CE supports a wide range of .NET assembly and application types, including Universal Windows
Platform (UWP) and Xamarin.
Application Monitoring
When developing an application, it is critical to understand the behavior patterns of users, including beta testers
and users of prior versions. Application analytics allows you to track how frequently the application is used and
how it is used, including what errors customers experience.
Dotfuscator CE can inject exception-tracking, session-tracking, and feature-tracking code into your application.
When run, the processed application will transmit analytics data to a configured PreEmptive Analytics endpoint.
See Also
This topic in the full Dotfuscator CE User Guide
Install Dotfuscator Community Edition (CE)
10/18/2017 • 1 min to read • Edit Online
Visual Studio 2017 introduces a new low-impact installation experience. As a result, Dotfuscator Community
Edition (Dotfuscator CE) is not installed by default. However, it is easy to install Dotfuscator CE even if you have
already installed Visual Studio.
NOTE
In addition to the versions of Dotfuscator CE shipped with releases of Visual Studio, PreEmptive Solutions also periodically
provides updated versions on its website. If you want to download the latest version directly instead of installing from
Visual Studio, click here to go to the Dotfuscator Downloads page.
2. In the Quick Launch results shown, under the Install heading, select PreEmptive Protection - Dotfuscator
(Individual Component).
If you instead see, under the Menus heading, Tools - PreEmptive Protection - Dotfuscator, then
Dotfuscator CE is already installed. For usage details, see the Getting Started page of the full Dotfuscator
CE User Guide.
3. A Visual Studio Installer window will launch, pre-configured with to install Dotfuscator CE.
You may be required to provide administrator credentials to continue.
4. Close all instances of the Visual Studio IDE.
5. In the Visual Studio Installer window, click Install.
Once the installation is complete, you can start using Dotfuscator CE. For details, see the Getting Started page of
the full Dotfuscator CE User Guide.
You can then install Dotfuscator CE as an individual component of Visual Studio 2017:
1. Select the Individual components tab.
2. Under Code tools, check the PreEmptive Protection - Dotfuscator item.
3. The Summary panel displays PreEmptive Protection - Dotfuscator under the Individual Components section.
See Also
This topic in the full Dotfuscator CE User Guide
Upgrade Dotfuscator Community Edition (CE)
10/18/2017 • 2 min to read • Edit Online
Dotfuscator Community Edition (Dotfuscator CE) offers many application protection and hardening features
immediately to all developers using Microsoft Visual Studio. However, there are more features available to users
who upgrade their version of Dotfuscator.
Registering Dotfuscator CE
Registered users of Dotfuscator CE get access to additional features, such as command line support, which makes
it easy to integrate Dotfuscator CE into your automated build process. In addition, registering will grant access to
Lucidator, a built-in tool used for decoding obfuscated stack traces.
Registration is quick, simple, and free of charge. To register Dotfuscator CE, see the Registering Dotfuscator CE
section on the Getting Started page of the full Dotfuscator CE User Guide.
Dotfuscator Professional
While Dotfuscator Community Edition provides a basic level of protection, PreEmptive Protection - Dotfuscator
Professional Edition includes enhanced obfuscation transforms and protection capabilities. These include:
Intellectual Property Protection
Additional renaming options, including Enhanced Overload Induction™ and randomized identifier
selection.
Tooling for decoding obfuscated stack traces.
Access to enterprise-level obfuscation transforms, including transforms targeted at defeating automated
code decompilation.
The ability to obscure sensitive strings, making a simple search of the decompiled code impossible.
The ability to discreetly embed ownership and distribution strings into your assemblies (software
watermarking), allowing you to determine the source of unauthorized software leaks.
The ability to combine multiple assemblies into one, making it even more difficult for attackers to
determine the roles of code elements, as separation of concerns has been eliminated.
The ability to automatically remove unused code from your application, reducing the amount of sensitive
code that is shipped.
Application Integrity Protection
Additional application defense behaviors.
The ability to provide a warning period before an application's end-of-life deadline.
The ability to notify application code during an end-of-life warning period or after the deadline.
Telemetry encryption.
Application Monitoring
The ability to collect and save collected information during temporary network outages.
The ability to collect personally-identifiable information.
Unlimited use of feature tracking.
The ability to track exceptions caught and thrown by your code, in addition to unhandled exceptions.
The ability to track exceptions in .dll assemblies.
Telemetry encryption.
Dotfuscator Professional is the industry standard .NET Obfuscator and is suitable for enterprise developers
requiring ongoing support, maintenance, and product updates. Additionally, Dotfuscator Professional offers tighter
integration with Visual Studio and is licensed for commercial use.
For more information on the advanced application protection features of Dotfuscator Professional, please visit
PreEmptive Solutions' Dotfuscator Overview page and compare it to Community Edition. Fully-supported trials are
available on request at preemptive.com.
See Also
This topic in the full Dotfuscator CE User Guide
Globalizing and Localizing Applications
10/18/2017 • 1 min to read • Edit Online
If you plan on distributing your application to an international audience, you'll need to keep several things in mind
during the design and development phases. Even if you don't have such plans, a small effort up front can make
things considerably easier should your plans change in future versions of your application. Services built into the
.NET Framework make it easy to develop a single application that can adapt to different locales using managed
development with Visual Studio.
Visual Studio was designed from the start to make developing for an international audience easy by taking
advantage of services built into the .NET Framework. The following pages will help introduce you to the
internationalization features built into Visual Studio.
In This Section
Introduction to International Applications Based on the .NET Framework
Introduces the concepts related to developing software for an international market using Visual Studio and the
.NET Framework.
Localizing Applications
Provides links to pages about customizing applications for a given culture.
Globalizing Applications
Provides links to pages about creating applications that support multiple cultures.
Related Sections
Globalizing your app (Windows Store apps using JavaScript and HTML)
Contains how-to topics and guidelines to help you globalize and localize your Windows 8.x Store app built using
JavaScript and HTML.
Globalizing your app (Windows Store apps using C#/VB/C++ and XAML)
Contains how-to topics and guidelines to help you globalize and localize your Windows 8.x Store app built using
XAML and Visual C#, Visual Basic, or Visual C++.
Best Practices for Developing World-Ready Applications
Provides background information on programming for an international audience.
Class Library Overview
Introduces the classes, interfaces, and value types that expedite and optimize the development process and
provide access to system functionality.
System.Globalization
Points out the classes in this namespace, which define culture-related information, including the language, the
country/region, the calendars in use, the format patterns for dates, currency and numbers, and the sort order for
strings.
System.Resources
Points out the classes and interfaces in this namespace, which allows developers to create, store, and manage
various culture-specific resources used in an application.
Introduction to International Applications Based on
the .NET Framework
10/18/2017 • 2 min to read • Edit Online
In Visual Studio, there are two parts to creating a world-ready application: globalization, the process of designing
applications that can adapt to different cultures, and localization, the process of translating resources for a specific
culture. For general information on designing applications for an international audience, see Best Practices for
Developing World-Ready Applications.
The .NET Framework localization model consists of a main assembly that contains both the application code and
the fallback resources — strings, images, and other objects for the language in which the application is originally
developed. Each localized application will have satellite assemblies, or assemblies which contain only the localized
resources. Because the main assembly always contains the fallback resources, if a resource is not found in the
localized satellite assembly, the ResourceManager will attempt to load it in a hierarchical manner, eventually
falling back to the resource in the main assembly. The resource fallback system is explained in greater detail in
Hierarchical Organization of Resources for Localization.
One localization resource you should consider using is the glossary for all Microsoft localized products. This CSV
file contains over 12,000 English terms plus the translations of the terms in up to 59 different languages. The
glossary is available for download on the Microsoft Terminology Translations Web page.
The project system for Windows Forms applications can generate resource files for both the fallback and each
desired additional UI culture. The fallback resource file is built into the main assembly, and the culture-specific
resource files are then built into satellite assemblies, one for each UI culture. When you build a project, the
resource files are compiled from the Visual Studio XML format (.resx) to an intermediate binary format
(.resources), which are then embedded in satellite assemblies.
The project system for both Windows Forms and Web Forms allows you to build resource files using an Assembly
Resource File template, access the resources, and build your project. Satellite assemblies will be created along with
the main assembly.
When a localized application executes, its appearance is determined by two culture values. (A culture is a set of
user preference information related to the user's language, environment, and cultural conventions.) The UI culture
setting determines which resources will be loaded. The UI culture is set as UICulture in Web.config files and page
directives, and CurrentUICulture in Visual Basic or Visual C# code. The culture setting determines formatting of
values such as dates, numbers, currency, and so on. The culture is set as Culture in Web.config files and page
directives, CurrentCulture in Visual Basic or Visual C# code.
See Also
System.Globalization
System.Resources
Globalizing and Localizing Applications
Security and Localized Satellite Assemblies
Localizing Applications
10/18/2017 • 1 min to read • Edit Online
Localization is the process of customizing your application for a given culture or locale. Localization consists
primarily of translating the user interface.
In This Section
Hierarchical Organization of Resources for Localization
Explains how localized resources are stored and accessed in Visual Studio.
Security and Localized Satellite Assemblies
Discusses signing satellite assemblies with public-private key pairs.
Version Numbers for Main and Localized Satellite Assemblies
Introduces the SatelliteContractVersionAttribute class, which determines which satellite assemblies work with an
application's main assembly.
Neutral Resources Languages for Localization
Introduces the NeutralResourcesLanguageAttribute class, which specifies the culture of the resources included in
an application's main assembly.
Related Sections
Introduction to International Applications Based on the .NET Framework
Discusses the concepts related to developing software for an international market using Visual Basic or Visual C#.
Globalizing Windows Forms
Provides links to pages about creating Windows applications that support multiple cultures.
Globalization and Localization
Provides links to pages about creating Web applications that support multiple cultures.
Best Practices for Developing World-Ready Applications
Provides information on programming for an international audience, such as design issues and terminology.
Hierarchical Organization of Resources for
Localization
10/18/2017 • 2 min to read • Edit Online
In Visual Studio, localized resources (data such as strings and images appropriate to each culture) are stored in
separate files and loaded according to the UI culture setting. To understand how localized resources are loaded, it
is useful to think of them as organized in a hierarchical manner.
If you follow the recommended practice of placing as many resources as possible in a neutral resource file
for the "fr" culture, the French Canadian user would not see resources marked for the "fr-BE" culture, but he
or she would be shown strings in French. The following situation shows this preferred scenario.
See Also
Neutral Resources Languages for Localization
Security and Localized Satellite Assemblies
Localizing Applications
Globalizing and Localizing Applications
How to: Set the Culture and UI Culture for Windows Forms Globalization
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
Security and Localized Satellite Assemblies
10/18/2017 • 1 min to read • Edit Online
If your main assembly uses strong naming, satellite assemblies must be signed with the same private key as the
main assembly. If the public/private key pair does not match between the main and satellite assemblies, your
resources will not be loaded. For more information on signing assemblies, see How to: Sign an Assembly with a
Strong Name.
In general, you may need to have your organization's signing group or an external signing organization sign with
the private key. This is due to the sensitive nature of the private key: access is often restricted to a few individuals.
You can use delayed signing during development. For more information, see Delay Signing an Assembly.
See Also
Assembly Security Considerations
Key Security Concepts
Introduction to International Applications Based on the .NET Framework
Localizing Applications
Globalizing and Localizing Applications
Version Numbers for Main and Localized Satellite
Assemblies
10/18/2017 • 1 min to read • Edit Online
The SatelliteContractVersionAttribute class provides versioning support for a main assembly that uses localized
resources by means of the resource manager. Applying the SatelliteContractVersionAttribute to an application's
main assembly allows you to update and re-deploy the assembly without updating its satellite assemblies. For
example, you can use the SatelliteContractVersionAttribute class with a service pack that doesn't introduce new
resources without rebuilding and redeploying your satellite assemblies. For your localized resources to be
available, the satellite contract version of your main assembly must match the AssemblyVersionAttribute class of
your satellite assemblies. You must specify an exact version number in the SatelliteContractVersionAttribute;
wildcard characters such as "*" are not allowed. For more information, see Retrieving Resources.
Updating Assemblies
The SatelliteContractVersionAttribute class allows you to update a main assembly without having to update your
satellite assembly, or vice versa. When the main assembly is updated, its assembly version number is changed. If
you want to continue using the existing satellite assemblies, change the main assembly's version number but leave
the satellite contract version number the same. For example, in your first release your main assembly version may
be 1.0.0.0. The satellite contract version and the assembly version of the satellite assembly will also be 1.0.0.0. If
you need to update your main assembly for a service pack, you can change the assembly version to 1.0.0.1, while
keeping the satellite contract version and the satellite's assembly version as 1.0.0.0.
If you need to update a satellite assembly but not your main assembly, you change the AssemblyVersionAttribute
of the satellite assembly. Along with your satellite assembly, you will have to ship a policy assembly that states that
your new satellite assembly is compatible with your old satellite assembly. For more information on policies, see
How the Runtime Locates Assemblies.
The following code shows how to set the satellite contract version. The code can be placed in either a build script or
in the AssemblyInfo.vb or AssemblyInfo.cs file.
<Assembly: SatelliteContractVersionAttribute("4.3.2.1")>
[assembly: SatelliteContractVersionAttribute("4.3.2.1")]
See Also
How the Runtime Locates Assemblies
Setting Assembly Attributes
Security and Localized Satellite Assemblies
Localizing Applications
Globalizing and Localizing Applications
Neutral Resources Languages for Localization
10/18/2017 • 1 min to read • Edit Online
The NeutralResourcesLanguageAttribute class specifies the culture of the resources included in the main assembly.
This attribute is used as a performance enhancement, so that the ResourceManager object does not search for
resources that are included in the main assembly.
The following code shows how to set the neutral resources language. The code can be placed in either a build
script or in the AssemblyInfo.vb or AssemblyInfo.cs file.
See Also
ResourceManager
Introduction to International Applications Based on the .NET Framework
Hierarchical Organization of Resources for Localization
Localizing Applications
Globalizing and Localizing Applications
Globalizing Applications
10/18/2017 • 1 min to read • Edit Online
Globalization is the process of designing and developing a software product that functions for multiple cultures.
This section applies to both Windows Forms and Web Forms pages.
In This Section
Culture-Specific Classes for Global Windows Forms and Web Forms
Discusses classes that format dates, time, numbers, currency, and other information according to the culture
setting.
Related Sections
Globalizing Windows Forms
Provides links to Help pages about globalization of Windows Forms.
Globalization and Localization
Provides links to Help pages about globalization of Web Forms pages.
Introduction to International Applications Based on the .NET Framework
Discusses the essential concepts about developing software for an international market using Visual Basic or Visual
C#.
Best Practices for Developing World-Ready Applications
Provides information on programming for an international audience, such as design issues and terminology.
Culture-Specific Classes for Global Windows Forms
and Web Forms
10/18/2017 • 1 min to read • Edit Online
Each culture has different conventions for displaying dates, time, numbers, currency, and other information. The
System.Globalization namespace contains classes that can be used to modify how culture-specific values are
displayed, such as DateTimeFormatInfo, Calendar, and NumberFormatInfo.
' Put the Imports statements at the beginning of the code module
Imports System.Threading
Imports System.Globalization
' Display a number with the culture-specific currency formatting
Dim MyInt As Integer = 100
Console.WriteLine(MyInt.ToString("C", Thread.CurrentThread.CurrentCulture))
If the culture is set to "fr-FR", you will see this in the output window:
100,00
If the culture is set to "en-US", you will see this in the output window:
$100.00
See Also
IFormattable.ToString
DateTimeFormatInfo
NumberFormatInfo
Calendar
Console.WriteLine
String.Format
Globalizing and Localizing Applications
Creating Applications in Bi-directional Languages
10/18/2017 • 4 min to read • Edit Online
You can use Visual Studio to create applications that correctly display text in languages written right-to-left,
including Arabic and Hebrew. For some features, you can simply set properties. In other cases, you must implement
features in code.
NOTE
In order to enter and display bi-directional languages, you must be working with a version of Windows that is configured
with the appropriate language. This can either be an English version of Windows with the appropriate language pack installed,
or the appropriately localized version of Windows.
NOTE
The code editor is a special case. For details, see below.
Data elements. Server Explorer will display these elements correctly and allow you to edit them.
Elements copied to the Windows Clipboard.
Attributes and metadata.
Property values. You can use Arabic or Hebrew text in the Properties window. The window allows you to
switch between right-to-left and left-to-right reading order using standard Windows keystrokes
(CTRL+RightShift for right-to-left, and CTRL+LeftShift for left-to-right).
Code and literal text. In the code editor (which is also the text editor), you can use Arabic or Hebrew to name
classes, functions, variables, properties, string literals, attributes, and so on. However, the editor does not
support right-to-left reading order; text always starts at the left margin.
TIP
It is recommended that you place string literals in resource files instead of hard-coding them into your programs. For
more information, see Walkthrough: Localizing Windows Forms.
NOTE
You must be consistent in how you refer to objects named in these languages. For example, if you use Kashida in
naming an Arabic variable, you must always use Kashida when referring to that variable, or errors will result.
Code comments. You can create comments in Arabic or Hebrew. You can also use these languages in the
comment builder tool.
See Also
Bi-Directional Support for Windows Forms Applications
Bidirectional Support for ASP.NET Web Applications
Globalizing Applications
Localizing Applications
How to: Save and Open Files with Encoding
10/18/2017 • 1 min to read • Edit Online
You can save files with specific character encoding to support bi-directional languages. You can also specify an
encoding when opening a file, so that Visual Studio displays the file correctly.
To save a file with encoding
1. From the File menu, choose Save File As, and then click the drop-down button next to the Save button.
The Advanced Save Options dialog box is displayed.
2. Under Encoding, select the encoding to use for the file.
3. Optionally, under Line endings, select the format for end-of-line characters.
This option is useful if you intend to exchange the file with users of a different operating system.
If you want to work with a file that you know is encoded in a specific way, you can tell Visual Studio to use
that encoding when opening the file. The method you use depends on whether the file is part of your
project.
To open an encoded file that is part of a project
1. In Solution Explorer, right-click the file and choose Open With.
2. In the Open With dialog box, choose the editor to open the file with.
Many Visual Studio editors, such as the forms editor, will auto-detect the encoding and open the file
appropriately. If you choose an editor that allows you to choose an encoding, the Encoding dialog box is
displayed.
3. In the Encoding dialog box, select the encoding that the editor should use.
To open an encoded file that is not part of a project
1. On the File menu, point to Open, choose File or File From Web, and then select the file to open.
2. Click the drop-down button next to the Open button and choose Open With.
3. Follow Steps 2 and 3 from the preceding procedure.
See Also
Encoding and Windows Forms Globalization
Globalizing and Localizing Applications
Adding Visual Studio editor support for other
languages
10/18/2017 • 2 min to read • Edit Online
Learn about how the Visual Studio editor supports reading and navigating through different computer languages
and how you can add Visual Studio editor support for other languages.
Visual Studio currently provides syntax colorization and basic statement completion support for the following
languages using TextMate Grammars. If your favorite language isn't in the table, though, don't worry - you can add
it.
In addition to syntax colorization and basic statement completion, Visual Studio also has a feature called Navigate
To. This feature enables you to quickly search code files, file paths and code symbols. Visual Studio provides
Navigate To support for the following languages.
Go
Java
JavaScript
PHP
TypeScript
Visual Basic
Visual C++
Visual C#
All of these file types have the features described earlier even if support for a given language hasn't yet been
installed. Installing specialized support for some languages may provide additional language support, such
as IntelliSense or other advanced language features such as Light Bulbs.
\<language name> The language folder. Replace <language name> with the
name of the language. For example, \Matlab.
\Syntaxes The grammar folder. Contains the grammar .json files for the
language, such as Matlab.json.
In Windows, %userprofile% resolves to the path: c:\Users\<user name>. If the extensions folder does not exist on
your system, you will need to create it. If the folder already exists, it will be hidden.
For details about how to create TextMate Grammars, see TextMate - Introduction to Language Grammars: How to
add source code syntax highlighting embedded in HTML and Notes on how to create a Language Grammar and
Custom Theme for a Textmate Bundle.
See Also
Visual Studio 2013 Navigate To Improvements
Walkthrough: Creating a Code Snippet
Walkthrough: Displaying Statement Completion
Using the Visual Studio Development Environment
for C#
10/18/2017 • 2 min to read • Edit Online
The Visual Studio integrated development environment (IDE) is a collection of development tools exposed through
a common user interface. Some of the tools are shared with other Visual Studio languages, and some, such as the
C# compiler, are unique to Visual C#. This topic provides links to the most important Visual C# tools.
Related Topics
TITLE DESCRIPTION
Walkthrough: Create a Simple Application Provides an overview of many of the features and tools
included in Visual Studio for application development.
Creating Solutions and Projects Describes how to create a project that contains all the source
code files, resource files such as icons, references to external
files, and configuration data such as compiler settings.
Writing Code Describes Visual Studio tools that help you modify and
manipulate text, code, and markup, insert and configure
controls and other objects and namespaces, and add
references to external components and resources.
Writing Code Provides links to procedures about how to use the Find and
Replace window, Bookmarks, and the Task List and Error List
to locate lines of code.
Viewing the Structure of Code Explains how to browse hierarchies of classes, class members,
and resources.
How to: Add an Application Configuration File to a C# Project Describes how to add a configuration file (app.config) to a C#
project.
Metadata as Source Describes how the IDE enables you to view metadata as
source code.
Refactoring (C#) Lists refactoring operations that help you modify your code
without changing the behavior of your application.
Code Generation (C#) Lists code generation tools that will write portions of code for
you.
TITLE DESCRIPTION
Compiling and Building Explains how to configure debug, release, and special builds of
your Visual Studio solution.
Debugging in Visual Studio Describes how to run the Visual Studio Debugger to resolve
logic and semantic errors.
Managing Application Resources (.NET) Shows how to add or edit resources for your project, such as
strings, images, icons, audio, and files.
Dotfuscator Community Edition (CE) Explains how to set up and start using the free PreEmptive
Protection - Dotfuscator Community Edition to protect .NET
assemblies from reverse-engineering and unauthorized use
(such as unauthorized debugging).
See Also
C#
Getting Started with C#
C# Reference
Visual Studio Reference
10/18/2017 • 1 min to read • Edit Online
This section includes user interface reference, language equivalents, and other reference documents.
In This Section
General User Interface Elements (Visual Studio)
Contains documents about dialog boxes and windows that are not described elsewhere in the table of contents.
Devenv Command Line Switches
Lists devenv command line switches.
Visual Studio Commands
Explains how to use Visual Studio commands from the Commands window.
XML Tools in Visual Studio
Contains documents about the XML tools in Visual Studio and provides links to more information.
MSBuild Contains documents about how to use the Microsoft build platform, which is integrated into Visual Studio.
Resources for Troubleshooting IDE Errors
Contains links to resources to help you resolve IDE error messages
Talk to Us
Contains information about how to locate customer support for Visual Studio.
Accessibility for People with Disabilities
Contains tips about how to change accessibility options.
Related Sections
Visual Basic Reference
Contains Visual Basic upgrading information and the Visual Basic language and run-time reference.
C/C++ Language and Standard Libraries
Contains language reference documentation.
JScript Reference
Contains documents about the JScript programming language. Includes properties, methods, objects, and
functions, and other elements.
.NET Framework Reference Information
Contains documents about the .NET Framework class library, compiler and language reference, and also ASP.NET
syntax, XSD reference, and other topics.