Creating Code Snippets – Part 1

Very recently i came across a very frustrating moment of my life. Guess what… I had to repeat a couple of lines of same code for about seventy two derived classes. Now that was too much. In this article i will show you something that might help. They are called code snippets. Many or almost all of you know what code snippets are, now lets discuss on how to create code snippets of your own.

Basically IntelliSense code snippets are in real xml files with a .snippet extension that adhere to the IntelliSense Code Snippet XML schema.

You can use any tool to generate the xml file but please remember to save it with a .snippet extension name.

Step 1, you add your root element as

<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>

Step 2, you add CodeSnippet element for the snippet you want to create as

<CodeSnippet Format=”1.0.0”>

Step 3, Now you need to add two sections within the CodeSnippet element, one is the Header element and the Snippet element.

Add the header section as

<Header>

        <Title> My CSharp Snippet </Title>

</Header>

Now add the snippet element that defines the snippet itself

<Snippet>

      <Code Language=”CSharp”>

      </Code>

</Snippet>

Please note the Language attribute also accepts the values CSharp, VJSharp, and XML. For more information, see Code Element (IntelliSense Code Snippets).

Now you the add the csharp code for the snippet within the code element. If you want the code to be inserted is

MessageBox.Show(“Hello World”);

then the element within the Code element would be

<![CDATA[MessageBox.Show(“Hello World”)]]>

Now your code snippet is ready. Go to Tools –> Manage Code Snippets –> Import to import your code snippet in Visual Studio.

The entire code -

<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>

         <CodeSnippet Format=”1.0.0”>

                <Header>

                           <Title> My CSharp Snippet </Title>

                 </Header>

                 <Snippet>

                             <Code Language=”CSharp”>

                                         <![CDATA[MessageBox.Show(“Hello World”)]]>

                              </Code>

                  </Snippet>

         </CodeSnippet>

</CodeSnippets>

Later i would discuss more about code snippets. Happy programming.

Advertisement
    • sankarsan
    • December 25th, 2009

    Nice to see you blogging again.

  1. No trackbacks yet.

You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.