달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30



https://msdn.microsoft.com/en-us/library/ms173063.aspx



TitleDescription
Walkthrough: Create a Simple ApplicationProvides an overview of many of the features and tools included in Visual Studio for application development.
Creating Solutions and ProjectsDescribes 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.
Introduction to the Project DesignerProvides an overview of the Project Designer, which provides a centralized location for managing project properties, settings, and resources.
Writing CodeDescribes 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.
Visual C# IntelliSenseProvides links to topics that describe Visual C#–specific features, such as automatic code generation and IntelliSense for most recently used members.
Visual C# Code SnippetsProvides an overview of using Code Snippets in Visual C# to automatically add common code constructs to your application
Writing CodeProvides 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 CodeExplains how to browse hierarchies of classes, class members, and resources.
How to: Add an Application Configuration File to a C# ProjectDescribes how to add a configuration file (app.config) to a C# project.
Metadata as SourceDescribes 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.
Compiling and BuildingExplains how to configure debug, release, and special builds of your Visual Studio solution.
Debugging in Visual StudioDescribes 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.




Walkthrough: Create a Simple Application with Visual C# or Visual Basic


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

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”-style application, design the UI, add code, and debug errors, while you learn more 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

System_CAPS_ICON_note.jpg Note

This walkthrough is based on Visual Studio Professional, which offers the WPF Application template on which you'll build the project for this walkthrough. Visual Studio Express for Windows Desktop also offers that template, but Visual Studio Express for Windows and Visual Studio Express for Web don't. For introductory information about how to use Visual Studio Express for Windows, see the Developer Center for Windows Store apps. For introductory information about how to use Visual Studio Express for Web, see Get Started with ASP.NET. In addition, your edition of Visual Studio and the settings that you use determine the names and locations of some elements of the user interface. See Customizing Development Settings in Visual Studio.

When you start Visual Studio for the first time, Visual Studio prompts you to sign in with a Microsoft Service Account (MSA), Sign into Visual Studio. You do not need to sign in and can do that later.

On your Visual Studio launch, you next must choose a settings combination that applies a set of pre-defined customizations to the IDE. Each settings combination has been designed to make it easier for you to develop applications.

This walkthrough assume you applied General Development Settings, which applies the least amount of customization to the IDE. If you have already chosen C# or Visual Basic (both are good choices), you don’t have to change your settings. If you want to change your settings, you can use the Import and Export Settings Wizard. See Customizing Development Settings in Visual Studio.

After you open Visual Studio, you can identify the 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.

Figure 2: Visual Studio IDE

IDE with General Settings Applied

You can make additional customizations to Visual Studio, such as changing the font face and size of the text in the editor or the color theme of the IDE, by using the Options dialog box. Depending on the settings combination that you’ve applied, some items in that dialog box might not appear automatically. You can make sure that all possible options appear by choosing the Show all settings check box.

Figure 3: Options dialog box

Options dialog box wirh Show all settings option

In this example, you’ll change the color theme of the IDE from light to dark. You can skip ahead to create a project if you like.

To change the color theme of the IDE

  1. Open the Options dialog box by choosing the Tools menu at the top and then the Options … item.

    Options command on the Tools menu

  2. Change the Color theme to Dark, then click OK.

    Dark color theme selected

The colors in Visual Studio should match the following image:

IDE with Dark Theme applied

The color theme used for pictures in the rest of this walkthrough is the light theme. For more information about customizing the IDE, see Customizing Development Settings in Visual Studio.

Create the project

When you create an application in Visual Studio, you first create a project and a solution. For this example, you’ll create a Windows Presentation Foundation (WPF) project.

To create the WPF project
  1. Create a new project. On the menu bar, choose FileNewProject….

    On the menu bar, choose File, New, Project

    You can also type New Project in the Quick Launch box to do the same thing.

    In the Quick Launch box, specify new project

  2. Choose the Visual Basic or the Visual C# WPF Application template by choosing in the left pane InstalledTemplatesVisual C#Windows, for example, and then choosing WPF Application in the middle pane. Name the project HelloWPFApp at the bottom of the New Project dialog.

    Create a Visual Basic WPF Project, HelloWPFApp

    OR

    Create a Visual C# WPF Project, HelloWPFApp

Visual Studio creates the HelloWPFApp project and solution, and the Solution Explorer shows the various files. The WPF Designer shows a design view and an 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:

Figure 5: Project items

Solution Explorer with HelloWPFApp files loaded

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. By using the project properties and property pages, you can display and change options for projects and solutions.

To change the name of MainWindow.xaml
  1. In the following procedure, you’ll give MainWindow a more specific name. In Solution Explorer, select MainWindow.xaml. You should see the Properties window, but if you don’t, choose the View menu and the Property Window item. Change the File Name property to Greetings.xaml.

    Properties window with File Name highlighted

    Solution Explorer shows that the name of the file is now Greetings.xaml, and if you expand the MainWindow.xaml node (by putting focus in the node and pressing the rightarrow key), you see the name of MainWindow.xaml.vb or MainWindow.xaml.cs is now Greetings.xaml.vb or Greetings.xaml.cs. This code file is nested under the .xaml file node to show they are very closely related to each other.

    System_CAPS_ICON_warning.jpg Warning

    This change causes an error that you will learn how to debug and fix in a later step.

  2. In Solution Explorer, open Greetings.xaml in the Designer view (by pressing the Enter key while the node has focus) and select the title bar of the window by using the mouse.

  3. In the Properties window, change the value of the Title property to Greetings.

The title bar for MainWindow.xaml now reads Greetings.

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, search for the TextBlock control.

    Toolbox with the TextBlock control highlighted

  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:

Figure 7: Greetings window with TextBlock control

TextBlock control on the Greetings form

The XAML markup should look something like the following:

<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Center" RenderTransformOrigin="4.08,2.312" Margin="237,57,221,238"><Run Text="TextBlock"/><InlineUIContainer><TextBlock TextWrapping="Wrap" Text="TextBlock"/>  

To customize the text in the text block
  1. In the XAML view, locate the markup for TextBlock and change the Text attribute: Text=”Select a message option and then choose the Display button.”

  2. If the TextBlock does not expand to fit the In the Design view, enlarge the TextBlock control (using the grab handles on the edges) so that it displays all the text.

  3. 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, search for the RadioButton control.

    Toolbox window with RadioButton control selected

  2. Add two RadioButton controls to the design surface by choosing the RadioButton item and dragging it to the window on the design surface twice, and 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:

    Figure 8: RadioButtons in the Greetings window.

    Greetings form with textblock and two radiobuttons

  3. In the Properties window for the left RadioButton control, change the Name property (the property at the top of the Properties window) to RadioButton1. Make sure you have selected the RadioButton and not the background Grid on the form; the Type field of the Property Window under the Name field should say RadioButton.

  4. In the Properties window for the right RadioButton control, change the Name property to RadioButton2, and then save your changes by pressing Ctrl-s or using the File menu item. Make sure you selected the RadioButton before changing and saving.

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 RadioButton1 by pressing the right mouse button while selecting RadioButton1, choose Edit Text, and then enter Hello.

  2. Open the shortcut menu for RadioButton2 by pressing the right mouse button while selecting RadioButton2, choose Edit Text, and then enter Goodbye.

The final UI element that you’ll add is a Button control.

To add the button control
  1. In the Toolbox, search for the Button control, and then add it to the design surface under the RadioButton controls by selecting Button and dragging it to the form in the design view.

  2. In the XAML view, change the value of Content for the Button control from Content=”Button” to Content=”Display”, and then save the changes (Ctrl-s or use the File menu).

    The markup should resemble the following example: <Button Content="Display" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="215,204,0,0"/>

Your window should resemble the following illustration.

Figure 9: Final Greetings UI

Greetings form with control labels

Add code to the Display Button

When this application runs, a message box appears after a user first chooses a radio button and then chooses the Display button. One message box will appear for Hello, and another will appear for Goodbye. To create this behavior, you’ll add code to the Button_Click event in Greetings.xaml.vb or Greetings.xaml.cs.

Add code to display message boxes
  1. On the design surface, double-click the Display button.

    Greetings.xaml.vb or Greetings.xaml.cs opens, with the cursor in the Button_Click event. You can also add a click event handler as follows (if the pasted code has a red squiggle under any names, then you probably did not select the RadioButton controls on the design surface and rename them):

    For Visual Basic, the event handler should look like this:

    Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)  
    
    End Sub  
    
    

    For Visual C#, the event handler should look like this:

    private void Button_Click_1(object sender, RoutedEventArgs e)  
    {  
    
    }  
    
    
  2. For Visual Basic, enter the following code:

    If RadioButton1.IsChecked = True Then  
        MessageBox.Show("Hello.")  
    Else RadioButton2.IsChecked = True  
        MessageBox.Show("Goodbye.")  
    End If  
    
    
    

    For Visual C#, enter the following code:

    if (RadioButton1.IsChecked == true)  
    {  
        MessageBox.Show("Hello.");  
    }  
    else  
    {  
        RadioButton2.IsChecked = true;  
        MessageBox.Show("Goodbye.");  
    }  
    
    
  3. Save the application.

Next, you’ll debug the application to look for errors and test that both message boxes appear correctly. The following instructions tell you how to build and launch the debugger, but later you might read Building a WPF Application (WPF) and Debugging WPF for more information.

Find and fix errors

In this step, you’ll find the error that we caused earlier by changing the name of the main window XAML file.

To start debugging and find the error
  1. Start the debugger by selecting Debug, then Start Debugging.

    Start Debugging command on the Debug menu

    A dialog box appears, indicating that an IOException has occurred: Cannot locate resource ‘mainwindow.xaml’.

  2. Choose the OK button, and then stop the debugger.

    Stop Debugging command on the Debug menu

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) in the XAML view (it cannot be opened in the Design view) by selecting the file and pressing Enter or by double clicking it.

  2. Change StartupUri="MainWindow.xaml" to StartupUri="Greetings.xaml", and then save the changes with Ctrl-s.

Start the debugger again (press F5). You should see the Greetings window of the application.

To debug with breakpoints

By adding some breakpoints, you can test the code during debugging. You can add breakpoints by choosing Debug on the main menu, then Toggle Breakpoint or by clicking in the left margin of the editor next to the line of code where you want the break to occur.

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.

    Toggle Breakpoint command on the Debug menu

    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 the F5 key 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 DebugStep 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. Press the SHIFT + F5 keys (press shift first, and while holding it down, press F5) to stop debugging.

  11. On the menu bar, choose DebugDisable 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, then 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.

    The Clean Solution command on the Build menu

  2. Change the build configuration for HelloWPFApp from Debug to Release by using the dropdown control on the toolbar (it says “Debug” currently).

    The Standard toolbar with Release selected

  3. Build the solution by choosing Build, then Build Solution or press the F6 key.

    Build Solution command on the Build menu

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.






Creating Solutions and Projects


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Projects are the logical containers for everything that's needed to build your application. When you create a project by choosing File | New | Project from the main menu, Visual Studio creates a solution to contain it. You can then add more new or existing projects to the solution if necessary. You can create projects from existing code files and you can create temporary projects (.NET only) that will be deleted when you are done with them.

System_CAPS_ICON_note.jpg 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 Import and Export Settings on the Tools menu. For more information, see Customizing Development Settings in Visual Studio.

File | New | Project from the main menu to bring up the New Project dialog. In the left pane under Intalled | Templates chose the programming language and platform or technology, then choose from the available templates in the middle pane.

In the New Project dialog, the Solution drop-down gives you the option to create the new project in a new or existing solution, or in a new instance of Visual Studio.

If you have a collection of loose source files, you can easily create a project that contains them. Choose File | New |Project From Existing Code to start the Create Project from Existing Code Files Wizard and follow the prompts.

System_CAPS_ICON_tip.jpg Tip

This option works best for relatively simple collections of files.

By working with temporary projects, you can create and experiment with a .NET project without specifying a disk location. When you create a project, you just select a project type and template and specify a name in the New Project dialog box. At any time while you are working with the temporary project, you can save it, or you can discard it.

You can create a project to target earlier versions of the .NET Framework by using the .NET Framework version drop-down menu at the top of the New Project dialog box. Set this value before selecting a project template, as only templates compatible with that .NET Framework version will appear in the list.

You must have .NET Framework 3.5 installed on your system to access framework versions earlier than 4.0.

You can use Visual Studio to download and install sample solutions from the MSDN Code Gallery.

You can download the samples individually, or you can download a Sample Pack, which contains related samples that share a technology or topic. You'll receive a notification when source code changes are published for any sample that you download.

For more information, see Visual Studio Samples.

Sometimes you might have a file that multiple projects refer to, or that contains text or miscellaneous data that logically belongs at the solution level rather than under a specific project. To add a single item to a solution:

  1. Right-click on the solution node in Solution Explorer and choose Add | New Item or Add | Existing Item.

Although a project must reside in a solution, you can create a solution that has no projects.

To create an empty solution

  1. On the File menu, click New and then click New Project.

  2. In the left pane, select Installed, select Other Project Types, and then select Visual Studio Solutions from the expanded list.

  3. In the middle pane, select Blank Solution.

  4. Set the Name and Location values for your solution, then click OK.

After you create an empty solution, you can add new or existing projects or items to it by clicking Add New Item or Add Existing Item on the Project menu.

Deleting Solutions

You can delete a solution permanently, but not by using Visual Studio. Before you delete a solution, move any projects that you might want to use again in another solution. Then use File Explorer to delete the directory that contains the .sln and .suo solution files.

System_CAPS_ICON_note.jpg Note

The .suo file is a hidden file that is not displayed under default File Explorer settings.

To delete a solution
  1. In Solution Explorer, right-click the solution to delete, and select Open folder in File Explorer.

  2. In File Explorer, navigate up one level.

  3. Select the directory containing the solution and press Delete.





Introduction to the Project Designer


A project's properties specify how a project is built and debugged, and which libraries it references, how and where it is published, and any security settings to use. Use the Project Designer to set the project's properties. To access an individual file's properties, use the Properties window.

The Project Designer provides a centralized location for managing project properties, settings, and resources. The Project Designer appears as a single window in the Visual Studio IDE, much the same as other designers, such as the Form or Class designers. It contains several pages that are accessed through tabs on the left-hand side.

Information entered into the Project Designer persists when you switch from one page to another, when you build the project, or when you close the designer. An Undo command is available on the Edit menu to roll back changes.

To access the Project Designer and set project properties

  1. In Solution Explorer, select the project. You cannot access the Project Designer if the project does not yet exist.

  2. On the Project menu, click projectname Properties.

  3. Select the property page to change or view by clicking its tab, or use CTRL+PAGE DOWN and CTRL+PAGE UP to move between the different pages.

  4. Set the properties.

The Project Designer has no OK or Cancel button. All property changes take immediate effect in the active project. However, the settings are committed to the project file only when you select one of the save options, or when you close the designer.

If a control is dimmed, it does not apply to the type of project that is active, or cannot be used in the project's current configuration.

If you have a multiple-project solution, you can use more than one instance of the Project Designer at a time.

NoteNote

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 Visual Studio Settings.

The pages and options available in the Project Designer vary by project type and by language. The available pages are listed in the following table.

Page

Description

Application page

Contains settings that describe the application and its behavior, such as application type, startup object, and assembly information. For more information, see the following topics:

Build page

Contains build instructions, including the configuration to build, conditional symbols, warning levels, and output information. Applies to Visual C# projects only. For more information, see the following topics:

Build Events page

Contains command-line instructions that the compiler performs before the build and after the build. You can also specify the conditions under which the post-build events are run. Applies to Visual C# projects only. For more information, see the following topics:

Compile page

Contains settings that control how an application is compiled. Applies to Visual Basic projects only. For more information, see the following topics:

Debug page

Contains settings that control how an application is debugged. For more information, see the following topics:

References page

Contains a list of components referenced by your project. This includes assemblies, COM components, project-to-project, and Web references. For more information, see the following topic:

Reference Paths page

Lists the directories to search for assemblies referenced by the project when the project is loaded. This setting is specific to the project, computer, and user.

Resources page

Allows you to manage resources for an application. This includes strings, images, icons, and other resources. For more information, see the following topic:

Services page

Allows you to enable and configure client application services. These services enable Windows-based applications to access Microsoft Ajax application services. For more information, see the following topics:

Settings page

Allows you to manage application settings such as dynamic properties and user preferences.

Signing page

Contains settings related to signing an assembly, such as key file name or key provider information. For more information, see the following topics:

Security page

Contains settings for security permissions; applies only to applications deployed by ClickOnce publishing. For more information, see the following topics:

Publish page

Contains settings for deploying your application by using ClickOnce technology. For more information, see the following topics:

Code Analysis page

Contains the code analysis tool that you can run on your code. The tool reports information about your assemblies, such as violations of the programming and design rules set forth in the Microsoft .NET Framework Design Guidelines. For more information, see the following topics:






Visual C# Code Snippets


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

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.

By default the following code snippets are included in Visual Studio.

Name (or shortcut)DescriptionValid locations to insert snippet
#ifCreates a #if directive and a #endif directive.Anywhere.
#regionCreates a #region directive and a #endregion directive.Anywhere.
~Creates a destructor for the containing class.Inside a class.
attributeCreates a declaration for a class that derives from Attribute.Inside a namespace (including the global namespace), a class, or a struct.
checkedCreates a checked block.Inside a method, an indexer, a property accessor, or an event accessor.
classCreates a class declaration.Inside a namespace (including the global namespace), a class, or a struct.
ctorCreates a constructor for the containing class.Inside a class.
cwCreates a call to WriteLine.Inside a method, an indexer, a property accessor, or an event accessor.
doCreates a dowhile loop.Inside a method, an indexer, a property accessor, or an event accessor.
elseCreates an else block.Inside a method, an indexer, a property accessor, or an event accessor.
enumCreates an enum declaration.Inside a namespace (including the global namespace), a class, or a struct.
equalsCreates a method declaration that overrides the Equals method defined in the Object class.Inside a class or a struct.
exceptionCreates a declaration for a class that derives from an exception (Exception by default).Inside a namespace (including the global namespace), a class, or a struct.
forCreates a for loop.Inside a method, an indexer, a property accessor, or an event accessor.
foreachCreates a foreach loop.Inside a method, an indexer, a property accessor, or an event accessor.
forrCreates a for loop that decrements the loop variable after each iteration.Inside a method, an indexer, a property accessor, or an event accessor.
ifCreates an if block.Inside a method, an indexer, a property accessor, or an event accessor.
indexerCreates an indexer declaration.Inside a class or a struct.
interfaceCreates an interface declaration.Inside a namespace (including the global namespace), a class, or a struct.
invokeCreates a block that safely invokes an event.Inside a method, an indexer, a property accessor, or an event accessor.
iteratorCreates an iterator.Inside a class or a struct.
iterindexCreates a "named" iterator and indexer pair by using a nested class.Inside a class or a struct.
lockCreates a lock block.Inside a method, an indexer, a property accessor, or an event accessor.
mboxCreates a call to MessageBox.Show. You may have to add a reference to System.Windows.Forms.dll.Inside a method, an indexer, a property accessor, or an event accessor.
namespaceCreates a namespace declaration.Inside a namespace (including the global namespace).
propCreates an auto-implemented property declaration.Inside a class or a struct.
ropfullCreates a property declaration with get and set accessors.Inside a class or a struct.
propgCreates a read-only auto-implemented property with a private "set" accessor.Inside a class or a struct.
simCreates a staticint Main method declaration.Inside a class or a struct.
structCreates a struct declaration.Inside a namespace (including the global namespace), a class, or a struct.
svmCreates a staticvoid Main method declaration.Inside a class or a struct.
switchCreates a switch block.Inside a method, an indexer, a property accessor, or an event accessor.
tryCreates a try-catch block.Inside a method, an indexer, a property accessor, or an event accessor.
tryfCreates a try-finally block.Inside a method, an indexer, a property accessor, or an event accessor.
uncheckedCreates an unchecked block.Inside a method, an indexer, a property accessor, or an event accessor.
unsafeCreates an unsafe block.Inside a method, an indexer, a property accessor, or an event accessor.
usingCreates a using directive.Inside a namespace (including the global namespace).
whileCreates a while loop.Inside a method, an indexer, a property accessor, or an event accessor.







Visual C# IntelliSense


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Visual C# IntelliSense is available when coding in the editor, and while you debugging in the Immediate Mode command window.

The IntelliSense completion lists in Visual C# contain tokens from List Members, Complete Word, and more. It provides quick access to:

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 in C# and Pre-selected Completion List Items in C#.

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 Element (Intellisense Code Snippets). 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.

System_CAPS_ICON_note.jpg 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.

  • as and is operators.

  • 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.

  • as and is Operators: A filtered completion list is displayed automatically when you press the SPACEBAR after you have typed the as or iskeyword.

  • 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.

IntelliSense remembers the members that you have recently selected in the pop-up List Members box for automatic object name completion. The next time you use Member List, the most recently used members are shown at the top. The history of most recently used members is cleared between each session in the IDE.

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.

Add using

The Add using IntelliSense operation enables you to maintain your focus on the code you are writing rather than requiring you to shift your focus to another part of the code.

To initiate the Add using operation, position the cursor on a type reference that cannot be resolved. For example, when you create a console application and then add XmlTextReader to the body of the Main method, a smart tag will appear under the rightmost character of XmlTextReader, since it appears as a type reference that cannot be resolved.

Add Using Smart Tag Image

You can then invoke the Add using by selecting it from Resolve submenu of the IntelliSense menu or the context menu, or by invoking Add using through the smart tag. The smart tag is only visible when the cursor is positioned on, or adjacent to, the unbound type.

Add using, smart tag expanded image

Organize usings

The Organize Usings options sort and remove using and extern declarations without changing the behavior of the source code. Over time, source files may become bloated and difficult to read because of unnecessary and unorganized using directives. The Organize Usings options compact source code by removing unused using directives and improves readability by sorting them.

To see the available options in the Visual Studio IDE, on the Edit menu, point to IntelliSense, and then point to Organize Usings. The IDE provides the following options to organize and remove usings directives:

Implement Interface

IntelliSense provides an option to help you implement an interface while working in the Code Editor. Normally, to implement an interface properly you must create a method declaration for every member of the interface in your class. Using IntelliSense, after you type the name of an interface in a class declaration, a smart tag is displayed. The smart tag gives you the option to implement the interface automatically, using explicit or implicit naming. Under explicit naming, the method declarations carry the name of the interface; under implicit naming, the method declarations do not indicate the interface to which they belong. An explicitly named interface method can only be accessed through an interface instance, and not through a class instance. For more information, see Explicit Interface Implementation.

Implement Interface will generate the minimum number of method stubs that is required to satisfy the interface. If a base class implements parts of the interface, then those stubs are not regenerated.

Implement abstract base class

IntelliSense provides an option to help you implement members of an abstract base class automatically while working in the Code Editor. Normally, to implement members of an abstract base class requires creating a new method definition for each method of the abstract base class in your derived class. Using IntelliSense, after typing the name of an abstract base class in a class declaration, a smart tag is displayed. The smart tag gives you the option to implement the base class methods automatically.

The method stubs that are generated by the Implement Abstract Base Class feature are modeled by the code snippet defined in the file MethodStub.snippet. Code Snippets are modifiable. For more information, see Walkthrough: Creating a Code Snippet.

Generate from usage

The Generate From Usage feature enables you to use classes and members before you define them. You can generate a stub for any class, constructor, method, property, field, or enum that you want to use but have not yet defined. You can generate new types and members without leaving your current location in code. This minimizes interruption to your workflow.

A wavy underline appears under each undefined identifier. When you rest the mouse pointer on the identifier, an error message appears in a tooltip.

To display the appropriate options, you can use one of the following procedures:

  • Click the undefined identifier. A short underline appears under the leftmost character. Rest the mouse pointer on the short underline, and a smart tag (an icon) appears. Click the smart tag.

  • Click the undefined identifier, and then press CTRL+. (period).

  • Right-click the undefined identifier, and then click Generate.

The options that appear can include the following:

  • Generate property stub

  • Generate field stub

  • Generate method stub

  • Generate class

  • Generate new type (for a class, struct, interface, or enum)

In the Code Editor, IntelliSense can help you hook up methods (event handlers) to event fields.

When you type the += operator after an event field in a .cs file, IntelliSense prompts you with the option to press the TAB key. This inserts a new instance of a delegate that points to the method handling the event.

Button Auto Hook Up

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.

Generate Event Handler

System_CAPS_ICON_note.jpg 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.

System_CAPS_ICON_note.jpg Note

Use the Navigate Backward command on the View menu (CTRL+-) to go back to the event hookup statement.

The following task shows how IntelliSense automatically hooks up an event handler named button1_Click to an event field named button1.Click.








Writing Code in the Code and Text Editor


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The Visual Studio editor provides many features that make it easier for you to write and manage your code. You can expand and collapse different blocks of code by using outlining. You can learn more about the code you are using by using IntelliSense, the Object Browser, and the Call Hierarchy. You can navigate inside your code by using features such as Navigate ToGo 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 2015 editor before, see Editing Your Code for a quick overview.

You can view your code in a number of different ways. To see a class view of your solution, you can open the Class View window or expand the nodes in the Solution Explorer under your class files.

You can search and replace text for single or multiple files. For more information, see Finding and Replacing Text. If you use regular expressions, note that find and replace now use .NET regular expressions. 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.

System_CAPS_ICON_important.jpg 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.

Syntax ColoringSome 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 MarksAs 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 ErrorCompiler ErrorWarning, and Other Error.
Brace MatchingWhen 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).
Line NumbersLine 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 TrackingThe 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 TextYou 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.
ZoomYou 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 SpaceBy 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.
PrintingYou 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.

You can set color printing options in the Tools/Options/Environment/Fonts and Colors dialog box. Choose Printer in the Show settings for list to customize color printing. You can specify different colors for printing a file than for editing a file.
Global Undo and RedoThe 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.

You can find a number of advanced features on the Edit/Advanced submenu. Not all these features are available for all types of code files.

Format DocumentSets the proper indentation of lines of code and moves curly braces to separate lines in the document.
Format SelectionSets the proper indentation of lines of code and moves curly braces to separate lines in the selection.
Tabify Selected LinesChanges leading spaces to tabs where appropriate.
Untabify Selected LinesChanges leading tabs to spaces. If you want to convert all the spaces in your file to tabs (or all the tabs to spaces), you can use the Edit.ConvertSpacesToTabs and Edit.ConvertTabsToSpaces commands. These commands do not appear in Visual Studio menus, but you can call them from the Quick Access window or the command window.
Make UppercaseChanges all characters in the selection to uppercase, or if there is no selection, changes the character at the insertion point to uppercase.
Make LowercaseChanges all characters in the selection to lowercase, or if there is no selection, changes the character at the insertion point to lowercase.
Validate DocumentValidates JScript code files.
Delete Horizontal White SpaceDeletes tabs or spaces at the end of the current line.
View White SpaceDisplays 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 WrapCauses 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).
Uncomment SelectionAdds comment characters to the selection or the current line.
Comment SelectionRemoves comment characters from the selection or the current line.
Increase Line IndentAdds a tab (or the equivalent spaces) to the selected lines or the current line.
Decrease Line IndentRemoves a tab (or the equivalent spaces) from the selected lines or the current line.
Select TagIn a document that contains tags (for example, XML or HTML), selects the tag.
Select Tag ContentIn a document that contains tags (for example, XML or HTML), selects the content.

You can move around in a document in several different ways. In addition to the standard operations, you can use the Navigate Backward (or CTRL + MINUS) and Navigate Forward (CTRL + SHIFT + MINUS) buttons on the toolbar to move the insertion point to previous locations or return to more recent locations in the active document. These buttons retain the last 20 locations of the insertion point.

Forward and back navigation buttons

You can also use the enhanced scroll bar in a code window to get a bird’s-eye view of your code. In map mode, you can see previews of the code when you move the cursor up and down the scroll bar, For more information, see How to: Track Your Code by Customizing the Scrollbar.

The following commands are code-specific navigation methods:

Go To <line number>(Edit/Go To or CTRL + G): Move to a specific line number in the active document.
Navigate To(Edit/Navigate To or CTRL + ,): Finds a symbol or file in the active solution. It helps you pick a good set of matching results from a query. You can search for keywords that are contained in a symbol by using camel casing and underscore characters to divide the symbol into keywords.
Find All References(context menu): Finds all the references to the selected element in the solution.
Go To Definition(context menu or F12): Finds the definition of the selected element.
Peek Definition(context menu or Alt+F12): Finds the definition of the selected element and displays it in a popup window. For more information, see How to: View and Edit Code by Using Peek Definition (Alt+F12).
Next Method, Previous Method(Edit/Next Method, Previous Method) In Visual Basic code files, use these commands to move the insertion point to different methods.
Reference HighlightingWhen 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.
Find code-related infoYou 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.

You can also use the navigation bar, that is, the two dropdown boxes displayed at the top of the code window, to navigate in a code file. This bar allows you to navigate directly to a particular type or to one of the members within a type. The navigation bar appears with Visual Basic, C#, and C++ code files.

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). You can navigate in the dropdown boxes as follows:

  • To shift focus from the code window to the navigation bar, press the shortcut key combination CTRL+F2.

  • To return focus from the navigation bar to the code window, press the ESC key.

  • To shift focus from item to item on the navigation bar, press the TAB key.

  • To select the Navigation bar item that has focus and return to the IDE, press the ENTER key

  • To navigate to a class or type, click its name in the left dropdown.

  • To navigate directly to a procedure in a class, click a procedure in the right dropdown.

In a partial class, members defined outside the current code file may be grayed out.

Visual Studio's "Navigate To" command does a focused search of your code to help you quickly find specified elements in code files, file paths and code symbols. Unlike other text searches such as Find or Find in Files, Navigate To limits its search to areas where actual code lives, such as files, forms and code modules. For example, if you search for a string in an ASP.NET web application using Find or Find in Files in the whole solution, you might get several hits, including instances of the string in code remarks. By using Navigate To, however, you might only get a single function, ignoring any instances of the string in code remarks.

Navigate code using Navigate To

  1. Open a solution or folder in Visual Studio.

  2. On the main menu, choose EditNavigate To, or press CTRL + ,.

    A small text box appears in the upper corner of the code editor.

  3. In the text box, enter the name of the code element you want to find.

    Navigate To window

    As you type, the results appear in a dropdown list below the text box.

  4. To go to an element, choose it in the list.

Filter your search

To limit your search to only code symbols, preface your Navigate To query with an "@" character. For example, if you search for @application, Navigate To displays, for example, only classes that have the word "application" in them.

If you use camel casing in your code, you can find code elements faster by entering only the capital letters of code element name. For example, if your code has a component called ViewSwitcher, you can find it by entering just the capital letters of the name ("VS") in the Navigate To window.

Navigate To window - searching with capitals

This feature is particularly helpful if your code has long names.

Import and Export Settings: You can share settings with another developer, have your settings conform to a standard, or return to Visual Studio default settings by using the Import and Export Settings Wizard on the Tools menu. You can change general settings or language and project-specific settings.

Keyboard Mapping: You can define new hotkeys or redefine existing ones in the Tools/Options/Environment/Keyboard settings. For more information about hotkeys, see Default Keyboard Shortcuts.

For information about language-specific editor options, see the following:







Viewing the Structure of Code


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

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.

System_CAPS_ICON_note.jpg 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.

Class View is shown as part of Solution Explorer as well as in a separate window. The Class View window displays the elements of an application. The upper pane displays namespaces, types, interfaces, enumerations, and classes, and the lower pane displays the members that belong to the type selected in the upper pane. By using this window, you can move to member definitions in the source code (or in the Object Browser if the element is defined outside your solution).

You do not have to compile a project to view its elements in Class View. The window is refreshed as you modify the code in your project.

You can add code to your project by selecting the project node and choosing the Add button to open the Add New Item dialog box. The code is added in a separate file.

If your project is checked in to source code control, every Class View element displays an icon that indicates the source code status of the file. Common source code control commands such as Check OutCheck In, and Get Latest Version are also available on the shortcut menu for the element.

Class View Toolbar

The Class View toolbar contains the following commands.

New FolderCreates a virtual folder or subfolder in which you can organize frequently-used elements. They are saved in the active solution (.suo) file. After you rename or delete an element in your code, it might appear in a virtual folder as an error node. To correct this problem, delete the error node. If you renamed an element, you can move it from the project hierarchy into the folder again.
BackNavigates to the previously selected item.
ForwardNavigates to the next selected item.
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.

Class View Settings

The Class View Settings button on the toolbar has the following settings.

Show Base TypesBase types are displayed.
Show Derived TypesDerived types are displayed.
Show Hidden Types and MembersHidden types and members (not intended for use by clients) are displayed in light gray text.
Show Public MembersPublic members are displayed.
Show Protected MembersProtected members are displayed.
Show Private MembersPrivate members are displayed.
Show Other MembersOther kinds of members are displayed, including internal (or Friend in Visual Basic) members.
Show Inherited MembersInherited members are displayed.
Show Extension MethodsExtension methods are displayed.

Class View Shortcut Menu

The shortcut menu in Class View may contain the following commands, depending on the kind of project selected.

Go To DefinitionFinds the definition of the element in the source code, or in the Object Browser, if the element is not defined in the open project.
Browse DefinitionDisplays the selected item in the Object Browser.
Find All ReferencesFinds the currently selected object item and displays the results in a Find Results window.
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.
CopyCopies the fully qualified name of the item.
Sort AlphabeticallyLists types and members alphabetically by name.
Sort by Member TypeLists types and members in order by type (such that classes precede interfaces, interfaces precede delegates, and methods precede properties).
Sort by Member AccessLists types and members in order by access type, such as public or private.
Group by Member TypeSorts 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.
Go To DefinitionDisplays the definition of the type or member in the source code, if available.
Go To ReferenceDisplays a reference to the type or member in the source code, if available.
View Call HierarchyDisplays the selected method in the Call Hierarchy window.

The Call Hierarchy window shows where a given method (or property or constructor) is called, and lists the methods that are called from that method. You can view multiple levels of the call graph, which shows the caller/callee relationships among the methods in a specified scope.

You can display the Call Hierarchy window by selecting a method (or property or constructor) and then choosing View Class Hierarchy on the shortcut menu. The display should resemble the following picture.

Call Hierarchy Multiple Nodes Open
Call Hierarchy window

By using the drop-down list on the toolbar, you can specify the scope of the hierarchy: the solution, the current project, or the current document.

The main pane displays the calls to and from the method, and the Call Sites pane displays the location of the selected call. For members that are virtual or abstract, an Overrides method name node appears. For interface members, an Implements method name node appears.

The Call Hierarchy window does not find method group references, which include places where a method is added as an event handler or is assigned to a delegate. To find these references, use the Find All References command.

The shortcut menu in the Call Hierarchy window contains the following commands.

Add as New RootAdds the selected node as a new root node.
Remove RootRemoves the selected root node from the tree view pane.
Go to DefinitionNavigates to the original definition of a method.
Find All ReferencesFinds in the project all the references to the selected method.
CopyCopies the selected node (but not its sub-nodes).
RefreshRefreshes the information.

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.

View NamespacesDisplays namespaces rather than physical containers, in the left pane. Namespaces stored in multiple physical containers are merged.
View ContainersDisplays physical containers rather than namespaces, in the left pane. View Namespaces and View Containers are mutually exclusive settings.
Show Base TypesDisplays base types.
Show Derived TypesDisplays derived types.
Show Hidden Types and MembersDisplays hidden types and members (not intended for use by clients), in light gray text.
Show Public MembersDisplays public members.
Show Protected MembersDisplays protected members.
Show Private MembersDisplays private members.
Show Other MembersDisplays other types of members, including internal (or Friend in Visual Basic) members.
Show Inherited MembersDisplays inherited members.
Show Extension MethodsDisplays extension methods.

Object Browser Shortcut Menu Commands

The shortcut menu in the Object Browser may contain the following commands, depending on the kind of item selected.

Browse DefinitionShows the primary node for the selected item.
Find All ReferencesFinds the currently selected object item and displays the results in a Find Results window.
Filter To TypeDisplays only the selected type or namespace. You can remove the filter by choosing the Clear Search button.
CopyCopies the fully qualified name of the item.
RemoveIf the scope is a custom component set, removes the selected component from the scope.
Sort AlphabeticallyLists types and members alphabetically by name.
Sort by Object TypeLists types and members in order by type (such that classes precede interfaces, interfaces precede delegates, and methods precede properties).
Sort by Object AccessLists types and members in order by access type, such as public or private.
Group by Object TypeSorts 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.
Go To DefinitionDisplays the definition of the type or member in the source code, if available.
Go To ReferenceDisplays a reference to the type or member in the source code, if available.
View Call HierarchyDisplays the selected method in the Call Hierarchy window.

The Code Definition window displays the definition of a selected type or member in the active project. The type or member can be selected in the code editor or in a code view window.

Although this window is read-only, you can set breakpoints or bookmarks in it. To modify the displayed definition, choose Edit Definition on the shortcut menu. This opens the source file in the code editor and moves the insertion point to the line where the definition begins.

Code Definition Shortcut Menu

The shortcut menu in the Code Definition window may contain the following commands, depending on the programming language.

Create Unit TestsCreates unit tests for the selected element.
Generate Sequence DiagramWhen a method is selected, generates a sequence diagram.
Create Private AccessorIf a unit test is present in the solution, generates a method that the test uses to access the code.
Go To DefinitionFinds the definition (or definitions, for partial classes) and displays them in a Find Results window.
Find All ReferencesFinds the references to the type or member in the solution.
View Call HierarchyDisplays the method in the Call Hierarchy window.
Show Calling TestsIf there are unit tests in the project, shows the tests that call the selected code.
Run Calling TestsIf there are unit tests in the project, runs the tests for the selected code.
BreakpointInserts a breakpoint (or a tracepoint).
Run to CursorRuns the program in debug mode to the location of the cursor.
CopyCopies the selected line.
OutliningStandard outlining commands.
Edit DefinitionMoves the insertion point to the definition in the code window.
Choose EncodingOpens the Encoding window so that you can set an encoding for the file.

Document Outline Window

You can use the Document Outline window in conjunction with designer views, such as the designer for a XAML page or a Windows Form designer, or with HTML pages. This window displays the elements in a tree view so that you can view the logical structure of the form or page and find controls that are deeply embedded or hidden.







How to: Add an Application Configuration File to a C# Project


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

By adding an application configuration file (app.config file) to a C# project, you can customize how the common language runtime locates and loads assembly files. For more information about application configuration files, see How the Runtime Locates Assemblies.

System_CAPS_ICON_note.jpg Note

The Windows Store doesn’t support System.Configuration. As a result, Store apps don’t contain an app.config template.

When you build your project, the development environment automatically copies your app.config file, changes the file name of the copy to match your executable, and then moves the copy to the bin directory.

To add an application configuration file to your C# project

  1. On the menu bar, choose ProjectAdd New Item.

    The Add New Item dialog box appears.

  2. Expand Installed, expand Visual C# Items, and then choose the Application Configuration File template.

  3. In the Name text box, enter a name, and then choose the Add button.

    A file that's named app.config is added to your project.







Metadata as Source


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Metadata as source enables you to view metadata that appears as C# source code in a read-only buffer. This enables a view of the declarations of the types and members (without implementations). You can view metadata as source by running the Go To Definition command for types or members whose source code is not available from your project or solution.

System_CAPS_ICON_note.jpg Note

When you try to run the Go To Definition command for types or members that are marked as internal, the integrated development environment (IDE) does not display their metadata as source, regardless of whether the referencing assembly is a friend or not.

You can view metadata as source in either the Code Editor or the Code Definition window.

When you run the Go To Definition command for an item whose source code is unavailable, a tabbed document that contains a view of that item's metadata, displayed as source, appears in the Code Editor. The name of the type, followed by [from metadata], appears on the document's tab.

For example, if you run the Go To Definition command for Console, metadata for Console appears in the Code Editor as C# source code that resembles its declaration, but without an implementation.

Metadata as Source

When the Code Definition window is active or visible, the IDE automatically executes the Go To Definition command for items under the cursor in the Code Editor and for items that are selected in Class View or the Object Browser. If the source code is not available for that item, the IDE displays the item's metadata as source in the Code Definition window.

For example, if you put your cursor inside the word Console in the Code Editor, metadata for Console appears as source in the Code Definition window. The source resembles the Console declaration, but without an implementation.

If you want to see the declaration of an item that appears in the Code Definition window, right-click the item and click Go To Definition.







Refactoring (C#)


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Refactoring is the process of improving your code after it has been written by changing the internal structure of the code without changing the external behavior of the code.

Visual C# provides the following refactoring commands on the Refactoring menu:

Visual Studio supports multi-project refactoring for projects that are in the same solution. All of the refactoring operations that correct references across files correct those references across all projects of the same language. This works for any project-to-project references. For example, if you have a console application that references a class library, when you rename a class library type (using the Rename refactoring operation), the references to the class library type in the console application are also updated.

Many refactoring operations provide an opportunity for you to review all the reference changes that a refactoring operation would perform on your code, before committing to those changes. For these refactoring operations, a preview reference changes option will appear in the refactoring dialog box. After selecting that option and accepting the refactoring operation, the Preview Changes Dialog Box will appear. Notice that the Preview Changes dialog box has two views. The bottom view will display your code with all the reference updates due to the refactoring operation. Pressing Cancel on the Preview Changes dialog box will stop the refactoring operation, and no changes will be made to your code.

If the compiler does not have a complete understanding of your program, and it is possible that the refactoring engine might not update all the appropriate references, the warning dialog box is displayed. This warning dialog box also provides an opportunity for you to preview your code in the Preview Changes dialog box before you commit changes.

System_CAPS_ICON_note.jpg Note

If a method contains a syntax error (which the IDE indicates with a red wavy underline), then the refactoring engine will not update any references to an element within that method. The example below illustrates this behavior.

By default, if you execute a refactoring operation without previewing reference changes and a compilation error is detected in your program, then the development environment displays this warning dialog box.

If you execute a refactoring operation that has Preview reference changes enabled and a compilation error is detected in your program, then the development environment will display the following warning message at the bottom of the Preview Changes dialog box, in lieu of displaying the Refactoring Warning dialog box:

Your project or one of its dependencies does not currently build. References may not be updated.

This refactoring warning is only available for refactoring operations that provide the Preview reference changes option.

Refactoring is error tolerant. In other words, you can perform a refactoring in a project that cannot build. However, in these cases the refactoring process might not update ambiguous references correctly.

The Verification Results dialog box can notify you if the refactoring engine detects compile errors or discovers that a refactoring operation inadvertently causes a code reference to bind to something different from what it was originally bound to (rebinding issue).

To turn on the verification results feature, on the Tools menu, click Options. In the Options dialog box, expand Text Editor, and then expand C#. Click Advanced and select the Verify results of refactoring check box.

The Verification Results dialog box distinguishes the difference between two kinds of rebinding issues.

References whose definition will no longer be the renamed symbol

This kind of rebinding issue occurs when a reference no longer refers to a renamed symbol. For example, consider the following code:

class Example  
{  
    private int a;  
    public Example(int b)  
    {  
        a = b;  
    }  
}  

If you use refactoring to rename a to b, this dialog box appears. The reference to the renamed variable a now binds to the parameter that is passed to the constructor instead of binding to the field.

References whose definition will now become the renamed symbol

This kind of rebinding issue occurs when a reference that previously did not refer to the renamed symbol now does refer to the renamed symbol. For example, consider the following code:

class Example  
{  
    private static void Method(object a) { }  
    private static void OtherMethod(int a) { }  
    static void Main(string[] args)  
    {  
        Method(5);  
    }  
}  

If you use refactoring to rename OtherMethod to Method, this dialog box appears. The reference in Main now refers to the overloaded method that accepts an int parameter instead of the overloaded method that accepts an object parameter.





Extract Method Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Extract Method is a refactoring operation that provides an easy way to create a new method from a code fragment in an existing member.

Using Extract Method, you can create a new method by extracting a selection of code from inside the code block of an existing member. The new, extracted method contains the selected code, and the selected code in the existing member is replaced with a call to the new method. Turning a fragment of code into its own method lets you quickly and accurately reorganize code for better reuse and readability.

Extract Method has the following benefits:

  • Encourages best coding practices by emphasizing discrete, reusable methods.

  • Encourages self-documenting code through good organization.

    When descriptive names are used, high-level methods can read more like a series of comments.

  • Encourages the creation of finer-grained methods to simplify overriding.

  • Reduces code duplication.

To use Extract Method

  1. Create a console application named ExtractMethod, and then replace Program with the following example code.

    class A  
    {  
        const double PI = 3.141592;  
    
        double CalculatePaintNeeded(double paintPerUnit, double radius)  
        {  
            // Select any of the following:  
            // 1. The entire next line of code.  
            // 2. The right-hand side of the next line of code.  
            // 3. Just "PI *" of the right-hand side of the next line  
            //    of code (to see the prompt for selection expansion).  
            // 4.  All code within the method body.  
            // ...Then invoke Extract Method.  
    
            double area = PI * radius * radius;  
    
            return area / paintPerUnit;  
        }  
    }  
    
    
  2. Select the code fragment you want to extract:

    double area = PI * radius * radius;  
    
    
  3. On the Refactor menu, click Extract Method.

    The Extract Method dialog box appears.

    Alternatively, you can also type the keyboard shortcut CTRL+R, M to display the Extract Method dialog box.

    You can also right-click the selected code, point to Refactor, and then click Extract Method to display the Extract Method dialog box.

  4. Specify a name for the new method, such as CircleArea, in the New Method Name box.

    A preview of the new method signature displays under Preview Method Signature.

  5. Click OK.

When you use the Extract Method command, the new method is inserted following the source member in the same class.

If the class is a partial type, then Extract Method generates the new method immediately following the source member. Extract Method determines the signature of the new method, creating a static method when no instance data is referenced by the code in the new method.

When you extract a method that has an unconstrained generic type parameter, the generated code will not add the ref modifier to that parameter unless a value is assigned to it. If the extracted method will support reference types as the generic type argument, then you should manually add the ref modifier to the parameter in the method signature.

If you try to extract part of an anonymous method that includes a reference to a local variable that is either declared or referenced outside the anonymous method, then Visual Studio will warn you about potential semantic changes.

When an anonymous method uses the value of a local variable, the value is obtained at the moment the anonymous method is executed. When an anonymous method is extracted into another method, the value of the local variable is obtained at the moment of the call to the extracted method.

The following example illustrates this semantic change. If this code is executed, then 11 will be printed to the console. If you use Extract Method to extract the region of code that is marked by code comments into its own method and then execute the refactored code, then 10 will be printed to the console.

class Program  
{  
    delegate void D();  
    D d;  
    static void Main(string[] args)  
    {  
        Program p = new Program();  
        int i = 10;  
        /*begin extraction*/  
            p.d = delegate { Console.WriteLine(i++); };  
        /*end extraction*/  
        i++;  
        p.d();  
    }  
}  

To work around this situation, make the local variables that are used in the anonymous method fields of the class.





Rename Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Rename is a refactoring feature in the Visual Studio integrated development environment (IDE) that provides an easy way to rename identifiers for code symbols such as fields, local variables, methods, namespaces, properties, and types. Rename can be used to change the names in comments and in strings and to change the declarations and calls of an identifier.

System_CAPS_ICON_note.jpg Note

When using Source Control for Visual Studio, get the latest version of sources before you try to perform rename refactoring.

Rename refactoring is available from the following Visual Studio features:

FeatureBehavior of Refactoring in the IDE
Code EditorIn the Code Editor, rename refactoring is available when you position the cursor on certain types of code symbols. When the cursor is in this position, you can invoke the Rename command by typing the keyboard shortcut (CTRL + R, CTRL + R), or by selecting the Rename command from a smart tag, shortcut menu, or the Refactor menu.
Class ViewWhen you select an identifier in Class View, rename refactoring is available from the shortcut menu and Refactor menu.
Object BrowserWhen you select an identifier in Object Browser, rename refactoring is only available from the Refactor menu.
Property Grid of the Windows Forms DesignerIn the Property Grid of the Windows Forms Designer, changing the name of a control will initiate a rename operation for that control. The Rename dialog box will not appear.
Solution ExplorerIn Solution Explorer, a Rename command is available on the shortcut menu. If the selected source file contains a class whose class name is the same as the file name, you can use this command to simultaneously rename the source file and execute rename refactoring.

For example, if you create a default Windows-based application and then rename Form1.cs to TestForm.cs, the source file name Form1.cs will change to TestForm.cs and the class Form1 and all references to that class will be renamed to TestForm. Note: The Undo command (CTRL+Z) will only undo rename refactoring in the code and will not change the file name back to the original name. 

If the selected source file does not contain a class whose name is the same as the file name, the Rename command in Solution Explorer will only rename the source file and will not execute rename refactoring.

When you execute Rename, the refactoring engine performs a rename operation specific for each code symbol, as described in the following table.

Code SymbolRename Operation
FieldChanges the declaration and usages of the field to the new name.
Local variableChanges the declaration and usages of the variable to the new name.
MethodChanges the name of the method and all references to that method to the new name. Note: When you rename an extension method, the rename operation propagates to all instances of the method that are in scope, regardless of whether the extension method is being used as a static method or an instance method. For more information, see Extension Methods.
NamespaceChanges the name of the namespace to the new name in the declaration, all using statements, and fully qualified names. Note:When renaming a namespace, Visual Studio also updates the Default Namespace property on the Application page of the Project Designer. This property cannot be reset by selecting Undo from the Edit menu. To reset the Default Namespace property value, you must modify the property in the Project Designer. For more information, see Application Page.
PropertyChanges the declaration and usages of the property to the new name.
TypeChanges all declarations and all usages of the type to the new name, including constructors and destructors. For partial types, the rename operation will propagate to all parts.

To rename an identifier

  1. Create a console application named RenameIdentifier, and then replace Program with the following example code.

    class ProtoClassA  
    {  
        // Invoke on 'MethodB'.  
        public void MethodB(int i, bool b) { }  
    }  
    
    class ProtoClassC  
    {  
        void D()  
        {  
            ProtoClassA MyClassA = new ProtoClassA();  
    
            // Invoke on 'MethodB'.  
            MyClassA.MethodB(0, false);  
        }  
    }  
    
    
  2. Place the cursor on MethodB, either in the method declaration or the method call.

  3. From the Refactor menu, select Rename. The Rename dialog box appears.

    You can also right-click the cursor, point to Refactor on the context menu, and then click Rename to display the Rename dialog box.

  4. In the New Name field, type MethodC.

  5. Select the Search in Comments check box.

  6. Click OK.

  7. In the Preview Changes dialog box, click Apply.

To rename an identifier using smart tags

  1. Create a console application named RenameIdentifier, and then replace Program with the following example code.

    class ProtoClassA  
    {  
        // Invoke on 'MethodB'.  
        public void MethodB(int i, bool b) { }  
    }  
    
    class ProtoClassC  
    {  
        void D()  
        {  
            ProtoClassA MyClassA = new ProtoClassA();  
    
            // Invoke on 'MethodB'.  
            MyClassA.MethodB(0, false);  
        }  
    }  
    
    
  2. In the declaration for MethodB, type or backspace over the method identifier. A smart tag prompt will appear below this identifier.

    System_CAPS_ICON_note.jpg Note

    You can only invoke rename refactoring using smart tags at the declaration of an identifier.

  3. Type the keyboard shortcut SHIFT+ALT+F10, and then press the DOWN ARROW to display the smart tag menu.

    -or-

    Move the mouse pointer over the smart tag prompt to display the smart tag. Then move the mouse pointer over the smart tag and click the DOWN ARROW to display the smart tag menu.

  4. Select the Rename '<identifer1>' to '<identifier2>' menu item to invoke rename refactoring without a preview of the changes to your code. All references to <identifer1> will automatically be updated to <identifier2>.

    -or-

    Select the Rename with preview menu item to invoke rename refactoring with a preview of the changes to your code. The Preview Changes dialog box will appear.

When you Rename a member that either implements/overrides or is implemented/overridden by members in other types, Visual Studio displays a dialog box that says the rename operation will cause cascading updates. If you click Continue, the refactoring engine recursively finds and renames all members in base and derived types that have implements/overrides relationships with the member being renamed.

The following code example contains members with implements/overrides relationships.

    interface IBase
    {
        void Method();
    }
    public class Base
    {
        public void Method()
        { }
        public virtual void Method(int i)
        { }
    }
    public class Derived : Base, IBase
    {
        public new void Method()
        { }
        public override void Method(int i)
        { }
    }
    public class C : IBase
    {
        public void Method()
        { }
    }

In the previous example, renaming C.Method() also renames Ibase.Method() because C.Method() implements Ibase.Method(). Next, the refactor engine recursively sees that Ibase.Method() is implemented by Derived.Method() and renames Derived.Method(). The refactor engine does not rename Base.Method(), because Derived.Method() does not override Base.Method(). The refactoring engine stops here unless you have Rename overloads checked in the Rename dialog box.

If Rename overloads is checked, the refactor engine renames Derived.Method(int i) because it overloads Derived.Method()Base.Method(int i)because it is overridden by Derived.Method(int i), and Base.Method() because it is an overload of Base.Method(int i).

System_CAPS_ICON_note.jpg Note

When you rename a member that was defined in a referenced assembly, a dialog box explains that renaming will cause build errors.

When you rename a property in anonymous types, the rename operation will propagate to properties in other anonymous types that have the same properties. The following examples illustrate this behavior.

var a = new { ID = 1};  
var b = new { ID = 2};  

In the preceding code, renaming ID will change ID in both statements because they have the same underlying anonymous type.

var companyIDs =  
    from c in companylist  
    select new { ID = c.ID, Name = c.Name};  
  
var orderIDs =  
    from o in orderlist  
    select new { ID = o.ID, Item = o.Name};  

In the preceding code, renaming ID will only rename one instance of ID because companyIDs and orderIDs do not have the same properties.






Encapsulate Field Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The Encapsulate Field refactoring operation enables you to quickly create a property from an existing field, and then seamlessly update your code with references to the new property.

When a field is public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, you can disallow direct access to fields.

To create the new property, the Encapsulate Field operation changes the access modifier for the field that you want to encapsulate to private, and then generates get and set accessors for that field. In some cases, only a get accessor is generated, such as when the field is declared read-only.

The refactoring engine updates your code with references to the new property in the areas specified in the Update References section of the Encapsulate Field dialog box.

To create a property from a field

  1. Create a console application named EncapsulateFieldExample, and then replace Program with the following example code.

    class Square  
    {  
        // Select the word 'width' and then use Encapsulate Field.  
        public int width, height;  
    }  
    class MainClass  
    {  
        public static void Main()  
        {  
            Square mySquare = new Square();  
            mySquare.width = 110;  
            mySquare.height = 150;  
            // Output values for width and height.  
            Console.WriteLine("width = {0}", mySquare.width);  
            Console.WriteLine("height = {0}", mySquare.height);  
        }  
    }  
    
    
  2. In the Code Editor, place the cursor in the declaration, on the name of the field that you want to encapsulate. In the example below, place the cursor on the word width:

    public int width, height;  
    
    
  3. On the Refactor menu, click Encapsulate Field.

    The Encapsulate Field dialog box appears.

    You can also type the keyboard shortcut CTRL+R, E to display the Encapsulate Field dialog box.

    You can also right-click the cursor, point to Refactor, and then click Encapsulate Field to display the Encapsulate Field dialog box.

  4. Specify settings.

  5. Press ENTER, or click the OK button.

  6. If you selected the Preview reference changes option, then the Preview Reference Changes window opens. Click the Apply button.

    The following get and set accessor code is displayed in your source file:

    public int Width  
    {  
        get { return width; }  
        set { width = value; }  
    }  
    
    

    The code in the Main method is also updated to the new Width property name.

    Square mySquare = new Square();  
    mySquare.Width = 110;  
    mySquare.height = 150;  
    // Output values for width and height.  
    Console.WriteLine("width = {0}", mySquare.Width);  
    
    

The Encapsulate Field operation is only possible when the cursor is positioned on the same line as the field declaration.

For declarations that declare multiple fields, Encapsulate Field uses the comma as a boundary between fields, and initiates refactoring on the field that is nearest the cursor and on the same line as the cursor. You can also specify which field you want to encapsulate by selecting the name of that field in the declaration.

The code that is generated by this refactoring operation is modeled by the encapsulate field code snippets feature. Code Snippets are modifiable. For more information, see Code Snippets.






Extract Interface Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Extract Interface is a refactoring operation that provides an easy way to create a new interface with members that originate from an existing class, struct, or interface.

When several clients use the same subset of members from a class, struct, or interface, or when multiple classes, structs, or interfaces have a subset of members in common, it can be useful to embody the subset of members in an interface. For more information about using interfaces, see Interfaces.

Extract Interface generates an interface in a new file and positions the cursor at the beginning of the new file. You can specify which members to extract into the new interface, the name of the new interface, and the name of the generated file using the Extract Interface dialog box.

To use Extract Interface

  1. Create a console application named ExtractInterface, and then replace Program with the following code

    // Invoke Extract Interface on ProtoA.  
    // Note:  the extracted interface will be created in a new file.  
    class ProtoA  
    {  
        public void MethodB(string s) { }  
    }  
    
    
  2. With the cursor positioned in MethodB, and click Extract Interface on the Refactor menu.

    The Extract Interface dialog box appears.

    You can also type the keyboard shortcut CTRL+R, I to display the Extract Interface dialog box.

    You can also right-click the mouse, point to Refactor, and then click Extract Interface to display the Extract Interface dialog box.

  3. Click Select All.

  4. Click OK.

    You see the new file, IProtoA.cs, and the following code:

    using System;  
    namespace TopThreeRefactorings  
    {  
        interface IProtoA  
        {  
            void MethodB(string s);  
        }  
    }  
    
    

This feature is only accessible when the cursor is positioned in the class, struct, or interface that contains the members that you would like to extract. When the cursor is in this position, invoke the Extract Interface refactoring operation.

When you invoke extract interface on a class or on a struct, the bases and interfaces list is modified to include the new interface name. When you invoke extract interface on an interface, the bases and interfaces list is not modified.






Remove Parameters Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Remove Parameters is a refactoring operation that provides an easy way to remove parameters from methods, indexers, or delegates. Remove Parameters changes the declaration; at any locations where the member is called, the parameter is removed to reflect the new declaration.

You perform the Remove Parameters operation by first positioning the cursor on a method, indexer, or delegate. While the cursor is in position, to invoke the Remove Parameters operation, click the Refactor menu, press the keyboard shortcut, or select the command from the shortcut menu.

System_CAPS_ICON_note.jpg Note

You cannot remove the first parameter in an extension method.

To remove parameters

  1. Create a console application named RemoveParameters, and then replace Program with the following code.

    class A  
    {  
        // Invoke on 'A'.  
        public A(string s, int i) { }  
    }  
    
    class B  
    {  
        void C()  
        {  
            // Invoke on 'A'.  
            A a = new A("a", 2);  
        }  
    }  
    
    
  2. Place the cursor on method A, either in the method declaration or the method call.

  3. From the Refactor menu, select Remove Parameters to display the Remove Parameters dialog box.

    You can also type the keyboard shortcut CTRL+R, V to display the Remove Parameters dialog box.

    You can also right-click the cursor, point to Refactor, and then click Remove Parameters to display the Remove Parameters dialog box.

  4. Using the Parameters field, position the cursor on int i, and then click Remove.

  5. Click OK.

  6. In the Preview Changes — Remove Parameters dialog box, click Apply.

You can remove parameters from a method declaration or a method call. Position the cursor in the method declaration or delegate name and invoke Remove Parameters.

System_CAPS_ICON_caution.jpg Caution

Remove Parameters enables you to remove a parameter that is referenced in the body of the member, but it does not remove the references to that parameter in the method body. This can introduce build errors into your code. However, you can use the Preview Changes dialog box to review your code before executing the refactoring operation.

If a parameter being removed is modified during the call to a method, the removal of the parameter will also remove the modification. For example, if a method call is changed from

MyMethod(param1++, param2);  

to

MyMethod(param2);  

by the refactoring operation, param1 will not be incremented.






Reorder Parameters Refactoring


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

Reorder Parameters is a Visual C# refactoring operation that provides an easy way to change the order of the parameters for methods, indexers, and delegates. Reorder Parameters changes the declaration, and at any locations where the member is called, the parameters are rearranged to reflect the new order.

To perform the Reorder Parameters operation, put the cursor on or next to a method, indexer, or delegate. When the cursor is in position, invoke the Reorder Parameters operation by pressing the keyboard shortcut, or by clicking the command from the shortcut menu.

System_CAPS_ICON_note.jpg Note

You cannot reorder the first parameter in an extension method.

To reorder parameters

  1. Create a class library named ReorderParameters, and then replace Class1 with the following example code.

    class ProtoClassA  
    {  
        // Invoke on 'MethodB'.  
        public void MethodB(int i, bool b) { }  
    }  
    
    class ProtoClassC  
    {  
        void D()  
        {  
            ProtoClassA MyClassA = new ProtoClassA();  
    
            // Invoke on 'MethodB'.  
            MyClassA.MethodB(0, false);  
        }  
    }  
    
    
  2. Place the cursor on MethodB, either in the method declaration or the method call.

  3. On the Refactor menu, click Reorder Parameters.

    The Reorder Parameters dialog box appears.

  4. In the Reorder Parameters dialog box, select int i in the Parameters list, and then click the down button.

    Alternatively, you can drag int i after bool b in the Parameters list.

  5. In the Reorder Parameters dialog box, click OK.

    If the Preview reference changes option is selected in the Reorder Parameters dialog box, the Preview Changes - Reorder Parameters dialog box will appear. It provides a preview of the changes in the parameter list for MethodB in both the signature and the method call.

    1. If the Preview Changes - Reorder Parameters dialog box appears, click Apply.

      In this example, the method declaration and all the method call sites for MethodB are updated.

You can reorder parameters from a method declaration or a method call. Position the cursor on or next to the method or delegate declaration but not in the body.






Compiling and Building in Visual Studio


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

You can use Visual Studio to build applications and to create assemblies and executable programs at frequent intervals during a development cycle. By building your code often, you can identify compile-time errors, such as incorrect syntax, misspelled keywords, and type mismatches, earlier. You can also detect and correct run-time errors, such as logic errors and semantic errors, by frequently building and running debug versions of the code.

When you have fully developed and sufficiently debugged a project or solution, you can compile its components in a Release build. By default, a Release build is optimized and designed to be smaller and run faster than a debug version. For more information, see Walkthrough: Building an Application.

You can build an application by using the default build options in the IDE, at a command prompt, or by using Team Foundation Build. Each of these options use MSBuild as the underlying technology, and each approach has specific benefits, as the following table shows.

Build MethodBenefitsFor more information
Using the IDE- You can more easily create and run builds immediately.
- You can run multi-processor builds for C++ and C# projects.
- You can customize some aspects of the build system.
Building and Cleaning Projects and Solutions in Visual Studio
Running an MSBuild command line- You can build projects without installing Visual Studio.
- You can run multi-processor builds for all project types.
- You can customize most areas of the build system.
MSBuild
Using Team Foundation Build- You can automate your build process. For example, you can build one or more projects nightly or every time that code is checked in. You can also build projects on shared build servers rather than on your development computer.
- You can quickly specify the code that you want to build, the tests that you want to run, and other common options.
- You can modify the build workflow, and as needed, create build activities to perform deeply customized tasks.
Build the application

When you create a project, default build configurations are defined for it, and a solution build configuration is assigned to it to provide context for builds. Solution configurations define how the projects in solution are built and deployed. Project configurations are a set of project properties that are unique for a platform and build type (for example, Release Win32). You can edit these default configurations, and you can create your own configurations. For more information, see Introduction to the Project Designer and NIB How to: Modify Project Properties and Configuration Settings.

From within the IDE, you can perform the following additional tasks:





Debugging in Visual Studio


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The Visual Studio debugger helps you observe the run-time behavior of your program and find problems. The debugger works with all Visual Studio programming languages and their associated libraries. With the debugger, you can break execution of your program to examine your code, examine and edit variables, view registers, see the instructions created from your source code, and view the memory space used by your application.

For a quick introduction to debugging and diagnostics in Visual Studio, see Debug, Profile, and Diagnose.

  • What’s New for the Debugger in Visual Studio 2015 Describes new functionality in Visual Studio 2015.

  • Debugger WindowsLists the different debugger windows.

  • Debugger Basics Discusses the fundamentals of using the Visual Studio debugger. Topics include debugging basics, execution control, attaching to a running program, Just-In-Time debugging, launching the debugger automatically, dumps, breakpoints, inspecting your program, handling exceptions, Edit and Continue, and using expressions in the debugger.

  • More Debugging FeaturesDescribes different debugging features.

  • Remote Debugging Describes how to set up and use remote debugging.

  • Debug Multithreaded Applications Describes how to debug multithreaded applications.

  • IntelliTrace Describes the IntelliTrace feature.

  • Debugging Applications Describes how to debug different kinds of applications.

  • Debugging User Interface Reference Provides reference information on the windows and dialog boxes you use when debugging your application. These topics are also available when you press F1 while you have focus on a debugging user interface element, such as the Breakpoints window.

  • Debug Interface Access SDK Describes the Microsoft Debug Interface Access Software Development Kit (DIA SDK). The DIA SDK provides access to debug information stored in program database (.pdb) files generated by Microsoft postcompiler tools.





Managing Application Resources (.NET)


For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

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.

In a managed code project, open the project properties window (right-click the project node in Solution Explorer and select Properties, or type project properties in the Quick Launch window, or type ALT + ENTER in the Solution Explorer window). Select the Resources tab. You can add a .resx file if your project does not contain one already, add and delete different kinds of resources, and modify existing resources.

To find out how to work with resources in C++ projects, see How to: Create a Resource.




































'프로그래밍 > C#' 카테고리의 다른 글

Thread 관련  (0) 2017.03.05
Sockets  (0) 2017.03.02
Getting Started with C#  (0) 2017.02.13
클래스 종류 헤드라인  (0) 2017.01.04
C# Keywords - Types  (0) 2016.12.29
:
Posted by 지훈2