Click here to Skip to main content
11,410,750 members (63,580 online)
Click here to Skip to main content

Do Smart coding using Code Snippets in .NET

, 19 Apr 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
You learn how to create your own Code Snippets and publish them to your Team to use them.
Code Snippet - Code Snippet is a small block of re-usable code or text. You can use code snippet to insert code (predefine code) in your development code.

Code Snippet in .NET - There are many snippets available in Visual Studio .NET IDE. Inserting snippet is so easy that it requires few mouse clicks and you can enjoy reusability. You can also import/include namespaces associated with particular code and refer to the associated assemblies for that code. Currently, snippets are available for C#, VB, J# and XML. Code snippets use XML file format. You can create your own snippets and add them using Code Snippet Manager.

Insert Code Snippets
  • Right click on your code (where you want to insert the block of snippet) and select “Insert Snippets…”.
  • It shows you a list of snippets available for your IDE like File Systems, Security, XML, Workflow, Connectivity and Networking, DataTypes etc.
  • Choose the applicable snippet and it will insert some code block in your code.
  • By changing variable/datatype name, IDE changes to all applicable places where the same variable/datatype is used. That means you do not require changing it manually.

A Code snippet from “common code patterns\properties and procedures -> Define a Property”.

Private newPropertyValue As Integer
Public Property NewProperty() As Integer
    Get
        Return newPropertyValue
    End Get
    Set(ByVal value As Integer)
        newPropertyValue = value
    End Set
End Property

On renaming newPropertyValue variable, IDE renames it at all applicable places. On changing data type (Integer) of newPropertyValue, IDE changes the data type for associated property and all applicable places.

Import Code Snippets to your IDE
If your IDE does not have all code snippets available or someone has sent you a Code Snippet (.snippet) file and you want to make it available for your IDE, just follow the following steps and import a code snippet to your IDE -
  • Open snippet folder of current version of .NET Framework for a specific language, say VB. By default, you can find all snippets at C:\Program Files\Microsoft Visual Studio 8\VB\Snippets\1033.
  • Create a folder, say “MyProjectName”.
  • Open “MyProjectName” folder.
  • Copy snippet file to “MyProjectName” folder, say “MySnippet.snippet”.
  • Now open VS 2005.
  • Open Code Snippet Manager. By default, Code Snippet Manager in VS 2005 should appear under the Tools menu. (Short cut Ctrl+K and Ctrl+B). If it is not there, then follow these sub steps.

    • Go to Tools in VS 2005.
    • Select Commands tab and select tools.
    • Look for Code Snippet Manager, and Drag it from Command up to the Tool menu.
    • Now Code Snippet Manager should appear under Tools menu. It should be available for every time.
  • Choose your language, say Visual Basic.
  • You should be able to see all Snippets available for Visual Basic.
  • If your created folder is not available, then you can locate it by clicking Add button.
  • You should see a '+' sign besides your folder. After expanding your folder, you can see your snippet, which you have copied.
  • Click on “Import” folder and browse to your snippet file (.snippet) and click “Open” button.
  • Click "OK" button on Code Snippet Manager window.
  • Follow instructions in earlier section “Insert Code Snippets”, you can now see that your copied code snippet is available.
  • Use it and do a smart coding.

Create your own Code Snippet

Consider a case where you are a part of a big development project and you have to use some assemblies at regular intervals. These assemblies have their own implementation logic. In that case, you (ideally a very senior developer) can create a code snippet and configure it on all developers system. This way, not all developers require any implementation logic, they just need to use code snippet. This way, you cannot only reuse the code, but also standardize your code.

How to create a Code Snippet?
Code Snippets use XML Format and getting store as .snippet file extension. Please follow the following steps to create a code snippet. In this example, we will add variable with our own data type, Service Dependency property, Namespace and associate assemblies.
  • Open your IDE and create a new XML file.
  • Right click on your XML code, and select “Insert Snippet...”. This will insert some block of XML code.
  • A basic snippet code is ready, now you just need to configure it according to your requirement.


    <Title>title</Title>
    <Author>author</Author>
    <Shortcut>shortcut</Shortcut>
    <Description>description</Description>

  • Change title, author, shortcut and description in header section. Title will appear as a snippet title.

    <Snippet>
           <References>
             <Reference> <Assembly>System.Data.Dll</Assembly> </Reference>      </References>
          <Imports>
            <Import> <Namespace>System.Data</Namespace> </Import>
            <Import> <Namespace>System.XML</Namespace>  </Import>
    </Imports>


  • Add assembly references associated with code snippet. Provide assemblies, which are required for your code block. IE if your code block requires System.Data.Dll, then you can add as reference.
  • Add associated namespace as import in Imports section. IE if your code requires System.Data and System.XML, then you can add both namespace in separate Import tag in Imports section.

    <Declarations>
          <Literal>
                <ID>name</ID>
                <Default>_myVariable</Default>
          </Literal>
          <Literal>
                <ID>variableType</ID>
                <Default>Integer</Default>
          </Literal>
    </Declarations>


  • Now you have to declare some literal, which will be used to define your code block; if you have a variable declaration, declare it in literal Tag.
  • You can provide variable name, method name, property name, user datatypes or any text information.
  • After providing all Literal tags, now you can create a code block. You must have to define code block as simple text as CDATA (Refer XML).

    <Code Language="VB">
          <![CDATA[Private $name$ As $variableType$]]>
               </Code>

  • Your snippet is ready, now you need to save it. To save your code snippet, please follow “Import Code Snippet” section of previous tip (Enterprise Architecture Tip of the week – Do Smart Coding Using Code Snippets – I).
  • When you use your code snippet in your code, IDE inserts a code block in your code, which looks like…
     Private _myVariable As Integer
  • This code snippet also imports System.Data and System.XML namespace and adds System.Data to References.
  • A code block created by a code snippet for my project, looks like…

    Private _gcpDAO As IGcpDAO
          &amp;lt;ServiceDependency()&amp;gt; _
                Public Property GcpDAO() As IGcpDAO
                  Get
           Return _gcpDAO
           End Get
                 Set(ByVal value As IGcpDAO)
                 _gcpDAO = value
           End Set
     End
So do start creating your own code snippets and do coding in a smarter way.

License

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

Share

About the Author

Joshi, Rushikesh
Technical Lead Synechron
United States United States
Having 12 Years of Software Development experience.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150414.5 | Last Updated 19 Apr 2011
Article Copyright 2011 by Joshi, Rushikesh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid