Share via


Visual Studio: Snippetty Tip


 

Introduction                 

Lots of developers use Intellisense Code Snippets but relatively few design their own or even alter existing snippets. Most don't even know they can do this.
They're reasonably well documented but Visual Studio is vast and if you don't think to search you would never find that documentation.
The main tip here is that most developers ought to be modifying existing snippets and adding their own.
Snippets are easy and can save you a fair bit of time in the long run.

This article assumes c# throughout  - you can use snippets with multiple languages although things like folder names will of course be different.

Audience

If you know how to change and write snippets already then this tip isn't for you.
If you don't then this could be pretty handy.
Does the standard formatting of existing snippets annoy you?
Do you find yourself typing similar statements repeatedly or cutting and pasting statements?
Do you have strong feelings on where your curly braces go, and or separating code across lines?
Do you frequently find yourself modifying code straight after a snippet inserts it?

Then this is for you.

What's a Code Snippet?

Some developers use these without actually knowing what they're called.
A snippet is one of those things which gives you a code template in the editor as you type a specific mnemonic.
For example, as you type prop and an intellisense window pops up with several options. Choose prop and tab tab to get a template inserted in your code:

public int MyProperty { get; set; }

With prop the type (int) and variable name (MyProperty) have a sort of yellow background to them. These are variables you can overtype and all instances change. Not so amazing with prop since there is only one occurrence of each, but handy with more complicated ones.

What and where are they?

Snippets go in a file with a .snippet extension and the official way to get at them is to use Tools > Code Snippet Manager.
Once you get the resulting window open you can navigate in the Treeview and or use the Language: Combobox to select which group of snippets to work on.
If you find our friend prop and click on it, you will see the location fills with a location on disk:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C#\prop.snippet

Or you could just use file manager to find that folder and get the file without using the Code Snippet Manager at all.
Cut and paste that address into file explorer and the file should open up in Visual Studio for you to take a look at.

    <?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>prop</Title>
            <Shortcut>prop</Shortcut>
            <Description>Code snippet for an automatically implemented property
Language Version: C# 3.0 or higher</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

If you take a look at the line

<Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>

This is the business end of the snippet - the part that produces c# in the editor once you tab off prop. The parts between $ such as $type$ are variables which are specified in the Declarations section, there you can see that type has a default of "int" and a descriptive tooltip "Property Type".
You could easily, for example, change that "int" to "string" if you use more string variables than int. Which shows how easy it is to change them.

<Literal>
    <ID>type</ID>
    <ToolTip>Property type</ToolTip>
    <Default>string</Default>
</Literal>

A Simple Change

Armed with a basic understanding of how snippets work then go find and open propfull.
It'll probably be in

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C#

Passing over the declarative parts, the critical lines to take a look at are:

<Code Language="csharp"><![CDATA[private $type$ $field$;
 
public $type$ $property$
{
    get { return $field$;}
    set { $field$ = value;}
}
$end$]]

Now...
if you ever change the setter of properties so they run some code as the setter is hit then you will probably find the first thing you do is separate that setter across 4 lines before you insert your method:

private Person currentLevel;
public Person CurrentLevel
{
    get { return currentLevel; }
    set
    {
        currentLevel = value;
        RaisePropertyChanged();
    }
}

Maybe separating those out onto different lines in the snippet would be an idea?
Whilst we're at it, maybe string would be a better default than int.

Save your original .snippet file somewhere safe - just in case.
Change to default string by over-typing int with string here:

<Literal>
    <ID>type</ID>
    <ToolTip>Property type</ToolTip>
    <Default>string</Default>
</Literal>

Change the formatting of the setter:

<Code Language="csharp"><![CDATA[private $type$ $field$;
    public $type$ $property$
    {
        get 
    { 
      return $field$;
    }
        set 
    { 
      $field$ = value;
    }
    }
    $end$]]>
</Code>

Save your changes.

The "proper" way to import snippets is using the Code Snippet Manager.
All this seems to do is copy or delete files though.
Import copies your snippet to:

My Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets

That's a bit of a nuisance if you just edited an existing snippet.
You will find you end up with two snippets suggested for propfull by intellisense.

You might therefore find it better to use File Manager.
Close Visual studio.
Delete your existing propfull.snippet ( you copied the original somewhere safe before you started - right? )
 ..... and copy your new file into: 

\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C# 

Let's give it a go.
Open Visual studio, Choose File > New > File > Choose Visual C# class
Try your modified snippet by typing propfull tab tab and you should see:

public class  Class1
{
    private string  myVar;
    public string  MyProperty
    {
        get
        {
            return myVar;
        }
        set
        {
            myVar = value;
        }
    }

From Editor

If you add the Snippet Designer you get an extra option on edit context menu "Export as Snippet" does pretty much as it says and allows you to create a snippet based on some code you have written.
This is rather less useful than one might imagine since snippets are fairly basic things and most options are already covered.

Advanced Snippets

If you ever used a switch snippet with an enumeration you might be thinking "Yee-Har! I can generate a stack of code by iterating... ".

There is bad news though. 
Unfortunately, that snippet uses one of three Functions. The other two give you class or type name for where the snippet is inserted.
Further bad news is that you can't even write your own functions.

If you want more sophisticated snippet like functionality which is customisable then Resharper is the Visual Studio add on to look at.
Resharper has Code Templates which offer much more functionality.
If you do a lot of development on your own machine then Resharper gives quite a productivity boost and the cost is probably justifiable on that basis.
Note: The author has no link whatsoever to JetBrains beyond liking their software.

You might possibly be able to do something with Roslyn and write your own add on - if you have the time.

See Also

Visual Studio 2013 Portal

Other Resources

MSDN Creating and Using Intellisense Code Snippets
Visually designing snippets
Creating your own snippets 
List of Snippets