Code Snippets in Visual Studio 2005
By Anand Kumar
Published: 10/27/2005
Reader Level: Beginner Intermediate
Rated: 4.75 by 4 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

Visual Studio 2005 express edition has lots of enhancements to increase developer  productivity; the "Code Snippet" is one of those enhancements. I am going to talk about how code snippets can help you to write code faster based on predefined templates. I am also going to demonstrate how to write custom code snippets.

The code snippet is integrated within the Visual Studio IDE, it helps to generate type definitions, member definitions, and construct minimal coding by a single click. In Beta 2 the code snippets are available for Visual Basic .NET, C# and J#. To access/invoke a code snippet select Edit | IntelliSense | Insert Snippet or select the  Insert Snippet option by  right-clicking your mouse as shown below.

[invoking  code snippet]

Once the code snippet popup-menu displays, select the desired code template. For example lets try to add a property to a class. To do this select the  prop option from the Insert Snippet popup-menu, the generated code for this operation looks like below

 [adding a property to the class ]

The preceeding task automatically generates a private variable called myVar and a property called MyProperty .The interesting point is if you change the data type or variable name it automatically updates in the property. The philosophy behind the code snippet is it generates a skeleton code of the desired type automatically by a single click.

You can find different types of code snippet templates in Visual Studio 2005 - such as class, interface, struct - all of which generate skeleton code with respect to type. For example prop generates a member variable (field) with set/get accessors,exception generates a code block for custom exceptions or you can generate code for different iterators, conditional operators, etc. At this stage you might be wondering how it generates code, and can I write my own code snippet? All the pre-define code snippets are define in XML files and you can write your own code snippets easily. To see the file path of the code snippet click on Tools | Code Snippet Manager.

[Code Snippet Manager]

Note: Have a look at location text box displaying the path where all the templates are available with a file extension .snippet for example prop code snippet template file name is prop.snippet.

Now lets explore the contents of the snippet file. Open prop.snippet (click on prop item from the list box, this path will be displayed in the location text box). A few important points to be noted in the file are:

  • It has two important sub-elements: <Header> and <Snippet>.
  • The <Header> sub-element talks about the basicdistinctiveness of the template such as title (look at <Title></Title>) , shortcut (look at <Shortcut></Shortcut> which displays in intellisens),  description (look at  <Description></Description> displays as tool tip) and snippetType .
  • The <Snippet> sub-element is the place where you need to specify the basic code. The <Declarations>element is meant for define the variables or type. In our example the prop.snippet defines two types, one is int (myVar) and second one is property name (MyProperty). In this sub-element you can see another element called <Default> which specifies the default value for the code snippet variable/type.The main part of<Snippet>sub-element is< Code > , this section deals with the code to be generated based on the information provided in <Declarations>element(s):

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

If you observe the code$type$ $field$ refers the typeandfield(<Literal>elementof <Declarations> node)

  • The root element of the XML file is   < CodeSnippet > < /CodeSnippet >

Simerlarly to the expnasation list we have another type of code snippet called Surround With IntelliSense. It also results in code generation. The difference is that Surround With IntelliSense based code snippets allow you to select a block of code statements before applying the expansion.

Now lets write a custom snippet. For demonstration purposes I am creating a singleton snippet and I am going to show you how to access the snippet. The XML representation of singleton class follows:

<?xmlversion="1.0"encoding="utf-8" ?>
<CodeSnippetsxmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippetFormat="1.0.0">
          <Header>
                   <Title>Singleton</Title>
                   <Shortcut>Singleton</Shortcut>
                   <Description>Code snippet for define singleton class</Description>
                   <Author>Anand Kumar</Author>
                   <SnippetTypes>
                             <SnippetType>Expansion</SnippetType>
                   </SnippetTypes>
          </Header>
          <Snippet>
                   <Declarations>
                             <Literal>
                                      <ID>classname</ID>
                                      <ToolTip>Class name</ToolTip>
                                      <Default>SingletonSample</Default>
                             </Literal>
                             <Literal>
                                      <ID>type</ID>
                                      <ToolTip>Instance Type</ToolTip>
                                      <Default>SingletonSample</Default>
                             </Literal>
                             <Literal>
                                      <ID>field</ID>
                                      <ToolTip>Single Instance of SingleSample</ToolTip>
                                      <Default>MySingleObj</Default>
                             </Literal>
                             <Literal>
                                      <ID>method</ID>
                                      <ToolTip>Get Instance Method</ToolTip>
                                      <Default>GetInstance</Default>
                             </Literal>
                   </Declarations>
                   <CodeLanguage="csharp">
                             <![CDATA[class $classname$
          {
            static private $classname$ $field$ = null;            
            protected $classname$()
            {
            }
            public static $classname$ $method$()
            {
                 if ($field$ == null)
                     $field$ = new $classname$();
                 return $field$;
            }
          }]]>
                   </Code>
          </Snippet>
</CodeSnippet>
</CodeSnippets>

The next step is to integrate our custom snippet with existing snippets. To do this click on Tools | Code Snippet Manager and click on Import button.

 

      [Integrating custom code snippet]   

Alternatively simply copy the .snippet file to the snippet folder ( i.e. <Drive Name>\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# ).

Now lets call the singleton snippet in our application. Place the cursor in your program file where ever you want and invoke the singleton code snippet.

[Singleton snippet and the generated code ]

Conclusion

Code Snippet makes our work very easy and increase the development productivity .The developers leverage the predefined snippets as well as custom templates (your own templates). If you have any problem in access the code snippet tool click here to download the tool.

About Author : Anand Kumar Raohas 3 years of experience in .NET development. His core expertise is developing robust service components, remoting and Web Service, as well as a passion for Microsoft Patterns and Practices and .NET performance.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help