Creating Code Snippets in Visual Studio 2010


In this article we will be seeing how we can create Code snippets in Visual Studio 2010. Code Snippets are very useful and can help us with writing standardized code easily and quickly. 

codeSnpt1.gif

Visual Studio creates an XML file as shown below:

codeSnpt2.gif

Now let's add our snippet.

codeSnpt3.gif

codeSnpt4.gif

codeSnpt5.gif

Let's modify the default snippet generated. I am going to add a snippet here to create a generic class.

I modify the snippet below:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <
Title>title</Title>
    <Author>author</Author>
    <Shortcut>GenericClass</Shortcut>
    <Description>description</Description>
    <SnippetTypes>
      <
SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </
Header>
  <
Snippet>
    <
Declarations>
      <
Literal>
        <
ID>name</ID>
        <Default>value</Default>
      </Literal>
    </
Declarations>
    <
Code Language="Csharp">
      <![CDATA[ 
public class A<T> where T : class
    {

    }
     
]]>
    </
Code>
  </
Snippet>
</
CodeSnippet>

Once modified Save the file as MySnippet.snippet.

codeSnpt6.gif

codeSnpt7.gif

codeSnpt8.gif

codeSnpt9.gif

Hit the Finish Button.

Now let's add a new file and see if the snippet works.

codeSnpt10.gif

You could insert the snippet as shown below :

codeSnpt11.gif

public class A<T> where T : class
{
 
}


Inserting Code snippets can make the code very standardized.
 

Up Next
    Ebook Download
    View all
    Learn
    View all