Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Code Snippet in Visual Studio

, 23 Jul 2010
Rate this:
Please Sign up or sign in to vote.
In this article, I have introduced how you could use code snippets in your program to enhance code productivity.

Code Snippet is one of the best and easiest ways for any developer to increase code productivity. As far I know, there are lots of people who don't know about this feature in Visual Studio. It is an interesting feature which helps you to get a template of your method or property to code it quickly.

I believe everyone knows about intellisense feature that is already there with Visual Studio. There is nothing more I could tell about this lovely feature. While browsing the list of objects in the intellisense window, you would have already seen a few icons. These icons provide a special meaning. Some of them signify keywords, some are custom types/classes, some are methods. One of these are code snippets.

In the above figure, you can see how a code snippet looks like. Here in the above code, I have just started typing pro.... You will see a prop menu item should be there, which is actually a code snippet for a property stub. If you use TAB to select prop and then press Tab again, you will see something similar to the one below:

A new Property will be created which has a return type as int and name of the property is MyProperty. As I am using VS 2010 to do this, you will see the automatic property initializer here. But for previous versions, you might see a little longer than this property. It will create a variable and also a Property to access that variable. In VS 2010, if you want that property snippet, you will have to use propfull.

In either case, use TAB to stop to each of the literals. If you change the int to float, the return type of the property will also change likewise. Similarly if you press TAB again, and change the name of the variable, it will also reflect to the property.

Just similar to properties, you can also apply code snippets to methods, structs, classes, etc.

Thus in the above figure, you can see that testm produces a TestMethod. Hence you can say code snippets enhance the code production to a huge extent.

You can now even add code snippets in the ASP.NET page.

Here using code snippet, I have added a new update panel. But to remind you, code snippet is added in aspx page in VS 2010.

Code Snippet Manager

Visual Studio comes with Code-snippet manager. This is a tool which enables you to change an existing code snippet and also enlist all the code snippets that are available within the IDE. To check the Code snippet manager, go to Tools menu of Visual Studio IDE and choose Code Snippet Manager.

In the above figure, you can see that you can easily manage the property / code snippets from within the Manager. You can get the location where the actual code snippets are installed. You can even import a new code snippet to your Visual Studio IDE. By default, the custom VS code snippets are loaded from MyDocuments/Visual Studio/Code Snippets.

Custom Code Snippet

Yes, in spite of a large number of code snippets available for the IDE, I always find something short while writing my code. All of us have unique coding styles. Visual Studio IDE offers custom code snippets that you can produce just by writing an XML schema definition and placing it on Code Snippets folder inside MyDocuments folder with custom extension .snippet.

Let us write a snippet which we need most of the times while writing code in WPF. We need to invoke events called OnPropertyChanged and OnPropertyChanging. Inspite of writing this several times, let's fix this issue somewhat.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propnch</Title>
            <Shortcut>propnch</Shortcut>
            <Description>Code snippet for property and backing field and ensure 
      that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
            <Author>Abhishek</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>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[<span class="code-SummaryComment">

    private $type$ $field$;

    public $type$ $property$
    {
        get 
        { 
            return $field$;
        }
        set 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]></span>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

So from the above code, you can see a new Property Snippet is added to the system. To try that, you just go to the code window and type propnch. It will produce the output.

Now let's explain this a bit.

We divide the whole XML into three parts:

1. The Header Section:

<Header>
    <Title>propnch</Title>
    <Shortcut>propnch</Shortcut>
    <Description>Code snippet for property and backing field and ensure that 
    it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
    <Author>Abhishek</Author>
    <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
</Header>

In this section, I defined the Title, which represents the name of the snippet. The shortcut defines what will appear in the intellisense menu. The description comes as a tooltip.
SnippetTypes defines the type of the snippet. In general we leave it as Expansion, but it also has few other types like Surroundswith and Refactoring.

2. Variables

In the second part, we define variables which we want to input during the use of it.

<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>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>

You can see in the above XML segment that I have defined literals like type which defaults to int, property which defaults to MyProperty and field which defaults to myVar. These variables can be accessed using $ sign, which indicates where these variables will be placed. In code, anything written inside $ sign will be replaced by users action.

3. Declaration

<Code Language="csharp"><![CDATA[<span class="code-SummaryComment">

    private $type$ $field$;

    public $type$ $property$
    {
        get 
        { 
            return $field$;
        }
        set 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]></span>
            </Code>
        </Snippet>

In the final part, we define the code. You can see that in my example, I used C# as my language. The code is written inside the Code element and we put parameters wrapped within $ sign as I have already told you that these will be replaced when we use it in code.

Thus you can see, the variables are replaced within the code while you use it. You can use TAB to move from one variable to another.

I hope you can create more snippets like this to enhance your IDE capabilities.

Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhishek Sur
Architect
India India
Did you like his post?
 
Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.
 
Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook
 
Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.
 
You can also mail him directly to abhi2434@yahoo.com
 
Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com
 
Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 29190621-May-11 9:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 24 Jul 2010
Article Copyright 2010 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid