Keyboard Shortcuts

Tabs

Close all tabs: Alt-W-L

Code Folding

Collapse all code sections: Ctrl-M-O
Expand all code sections: Ctrl-M-L

To set that folding/outlining toggles always be visible:
    Tools > Options > Text Editor > C# > Advanced > check "Enter Outlining Mode When File Opens"

Navigation

Go to line number: Ctrl-G
Options

Verbosity

menu Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity
Default: Minimal
Full: Diagnostic

Code Style

VS can provide suggestions for refactoring based on a set of coding style standards.

There are defaults in the Options dialog.
The defaults will be overridden by the .editorconfig file in the root directory of the project.

Ex:

 # Prefer method-like constructs to have an expression body
 csharp_style_expression_bodied_methods = true:error
 csharp_style_expression_bodied_constructors = true:error
 csharp_style_expression_bodied_operators = true:error
This will underline block bodies in red (because "error") with the suggestion to refactor them to expression bodies.

Editorconfig

Applies to .Net in general.

File .editorconfig, located at solution/project root, enforces coding conventions for a whole solution/project.

Format

Example

    # http://editorconfig.org
    root = true

    # Global settings
    [*]
    max_line_length = 0
    charset = utf-8
    indent_size = 2
    indent_style = space
    insert_final_newline = true
    trim_trailing_whitespace = true

    # Markdown
    [*.md]
    trim_trailing_whitespace = false

    # Dotnet code style settings
    [*.{cs,vb}]
    indent_size = 4
    indent_style = tab

    # Sort using and Import directives with System.* appearing first
    dotnet_sort_system_directives_first = true

    # Avoid "this." and "Me." if not necessary
    dotnet_style_qualification_for_field = false:error
    dotnet_style_qualification_for_property = false:error
    dotnet_style_qualification_for_method = false:error
    dotnet_style_qualification_for_event = false:error
Scaffolding

Scaffolding will quickly fill in basic code structures.

Implement Interface

Your class will implement an interface. You don't want to type in all those method signatures yourself.

1) Add the interface to the inheritance of the class

public class MyClass : ISomeInterface
{
}

2) Right-click on the interface > Quick Actions and Refactorings > Implement Interface

You'll see all the method signatures filled in with NotImplementedException statements.
Projects

Start Multiple

You can start multiple projects in on solution at the same time, with debugging enabled.

Solution > right-click > Properties > Common Properties > Startup Project
Select "multiple startup projects" and set Action to "start" on the ones you want to debug.

Sync Inherited NuGet Package

Scenario:
- MyProject references NuGet package version 1.0
- TestProject references MyProject and inherits the NuGet package reference 1.0
- I update MyProject to reference version 1.1
- TestProject is still referencing version 1.0

Solution:
- In TestProject, remove dependency/reference to MyProject
- In TestProject, add dependency/referene to MyProject back in

This will force TestProject to update its inherited NuGet references.
Editors

You can change the default editor a file type opens in by:
- Right-Clicking on the file
- Open With...
- select the editor from the list of choices
- click Set As Default

I use this so my WinForms open in Source View instead of Design View.
Solution

Rename

Fully backup your solution before attempting manual rename operations.

1) Close Visual Studio

2) Rename the solution directory with version control
- If using Git source control, rename in Windows Explorer

3) Open *.sln file in a text editor
4) Replace all "OldProject" references with "NewProject"
5) Save changes to *.sln
6) Rename *.sln

7) Open *.csproj file in a text editor
8) Replace all "OldProject" references with "NewProject"
9) Save changes to *.csproj
10) Rename *.csproj

11) Reopen solution in Visual Studio
12) Rename any namespaces in project that have changed

13) If using Git, update .gitignore with new paths

XML Documentation

Type three forward slashes (///) in the line directly above a method or class to initiate a template for documenting that part of your code.

These special comments will provide information for IntelliSense and API documentation.


/// <summary>
/// Description of the purpose of the method.
/// </summary>
public void MyMethod()
{
}

These special comments are not included in the compiled assembly and are not available through reflection.

To enable generation of automated documentation files from these comments:
1) Open project properties
2) Go to Build tab
3) Check "XML documentation file"
4) (optional) change the default documentation file location
5) Build the project

[See all tags here.]

Processors

There are many tools available to convert the XML documentation into a web page or Markdown - Sandcastle and DocFX, for instance.

[This is my tool.]
It generates a collection of Markdown documents, one for each Type. It pulls information from the XML documentation and the DLL itself (if available).

Resources

To include an image in a class library, it must be a Resource in the project.
To add a Resource:
1) Open project properties
2) Go to the Resources tab
3) Click Add Resource in tool bar and select the type of file you are adding
4) Name the Resource as you would a constant
5) Resources will be added in "Resources" folder in project
6) Select resource file to see properties
7) Set Build Action to "None"
8) Set Copy to Output Direction to "Copy Always"

To access a Resource in the code:

Image myImage = MyNamespace.Properties.Resources.MY_IMAGE;

Breakpoints

Keyboard Shortcuts

F9 to add/remove breakpoint on the current line.

There is no default shortcut to disable all breakpoints, but you can do this from Debug > Disable All Breakpoints.

Breakpoints Window

Open with: Debug menu > Windows > Breakpoints
Or: Ctrl-Alt-B

You can:
- Deactivate breakpoints without deleting them (just uncheck the line)
- Set a condition on when the breakpoint is used (ex: 124th iteration of loop)
- WhenHit lets you output a message to the Output Window instead of breaking

Autos Window

The Autos Windows displays variables used in the current (about to be executed) and previous statements.

Debug menu > Windows > Autos
(only available during debugging)

When on a break, you can double-click a value and change it. (Or single-click, tab)
Immediate Window

The Immediate Window lets you enter expressions to be evaluated during debugging, in the current scope of the breakpoint.

Debug menu > Windows > Immediate
or Ctrl-Alt-I


Debug.Print variableA


? variableA //same as Debug.Print
Output Window

View menu > Output
or Ctrl-Alt-O

Right-click in the window to see the message categories you can turn on and off.
Class View Window

View menu > Class View > right-click on Namespace > View Class Diagram

This actually generates a class diagram file (*.cd) in your solution directory.

The diagram shows inheritance relationships, class fields, and class methods. It does not show which classes rely on each other.
Plugins

Display Images In Code

It would be very useful to include small diagrams in comments of certain test cases.

[Microsoft Image Insertion]
Can't get the installation working, even though it says it is supported by Visual Studio 2010 and I'm on 2015.

3rd party solutions:

[ImageComments Website]
and
[Memful Comments Website]

Both extensions only support Visual Studio version 15 and above, so I can't test them with VS Community 2015.

T4

T4 stands for Text Template Transformation Toolkit.

This is a built-in tool in Visual Studio. As of 2016, it does not have any intellisense or syntax highlighting support.

It is a mixture of text blocks and control logic that can generate a text file, using C# or Visual Basic.

Add a "Text Template" file to your project to create a T4 file. The generated file will be listed under it.
To re-generate the file: Right-click >> Run Custom Tool
To debug generation: Right-click >> Debug T4 Template

Run Time

Runtime T4 templates are run by your program. The computer running the program does not have to have Visual Studio installed.


string response = new MyTemplate().TransformText();

Design Time

Design time T4 templates are executed in Visual Studio to define part of your source code or other resources.

To do this, add a "Text Template" file to your project (*.tt extension). Or add a plain text file and set property "Custom Tool" to "TextTemplatingFileGenerator".

Default Contents


<#@ template debug="true" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
//any plain text below here will output as-is

If this file is called x.tt, it will generate file x.txt.

You can leave the debug statement in even when in Release mode. It is required for setting breakpoints in the template.

Include Assembly

You do not need to include assembly System.dll, it is assumed.


<#@ assembly name="MyAssembly.dll" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.IO" #>

Confirmed that a design-time T4 template can use assemblies that are for a higher target framework than the current project.

Standard Control Block

Contains statements.
Embed plain text to print it directly to the output file.


    <#
    int count = 10;
    for(int i=0; i<=count; i++)
    {
        #>
        The square of <#= i #> is <#= i*i #>.
        <#
        //OR
        WriteLine(String.Format("The square of {0} is {1}.", i, i*i));
    }
    #>
 
    <# 
    //another code block
    MyFunction(5);
    #>

Expression Control Block

Contains expressions that resolve to strings that are printed to the output file.


    <#
    for(int i=0; i<=10; i++)
    {
        #>
        The square of <#= i #> is <#= i*i #>.
        <#
    }
    #>

Class Feature Control Block

Contains methods, fields, properties, and nested classes.
Usually used for helper functions.

You cannot place Standard Control Blocks after a Class Feature Control Block in the T4 file.
This restriction does not apply to "<#@include#>" commands.


    <#+ //defines a method block 
    private void MyFunction(int x)
    {
        #>
        some output
        <#+
    }
    #>

Read File

Reading a text file:

<# var properties = File.ReadLines("C:\\propertyList.txt"); #>
...
<# 
    foreach(string property in properties)
    {
        ...
    }
 #>

Using a relative path name:

<#@ template hostspecific="true" language="C#" #>
<# string filename = this.Host.ResolvePath("file.txt"); #>

Getting the name of this template file:

<# string currentFilename = this.Host.TemplateFile; #>

Variables

Output variables:

Plain text and then <#= myVariable #>

Error Handling

Errors and warnings:

<# Error("message"); #>
<# Warning("message"); #>

Multiple Output Files


    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ assembly name="System.Core" #>
    <#@ import namespace="System" #>
    <#@ import namespace="System.IO" #>
    <#@ output extension=".txt" #>
    <#
    for (Int32 i = 0; i < 10; ++i) 
    {
    #>
        Content <#= i #>
    <#
        SaveOutput("Content" + i.ToString() + ".txt");
    }
    #>
    
    <#+
    private void SaveOutput(string outputFileName) 
    {
        string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string outputFilePath = Path.Combine(templateDirectory, outputFileName);
        File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
        this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
    }
    #>

Indentation

Managing indentation with built-in fields and methods.


    WriteLine(CurrentIndent + "A");
    PushIndent("\t");
    WriteLine(CurrentIndent + "A2");
    PopIndent("\t");
    WriteLine(CurrentIndent + "B");
    
    ClearIndent();

Visual Studio Errors

Access Is Denied

A generic error with no details. Occurs when you run a project.

1) Try closing and reopening Visual Studio. This sometimes fixes the problem.

2) ?