How to Create Code Snippet Using C#


In this article I will discuss how to create a code snippet. Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code during presentations. Instead of typing everything live, I find it far easier to simply add the code block by block using code snippets.

Fallow the steps to create a code snippet using Visual Studio 2010.

CodeSnpt1.gif

Default Blank XML:

CodeSnpt2.gif

Default snippet generated XML tags:

CodeSnpt3.gif

Modified XML tags.

Add the SQL Connection Code to ![CDATA[]]

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <
Title>SqlInsert</Title>
    <Author>Ravindra</Author>
    <Shortcut>SqlIns</Shortcut>
    <Description>Sql Connection</Description>
    <SnippetTypes>
      <
SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </
Header>
  <
Snippet>
    <
Declarations>
      <
Literal>
        <
ID>message</ID>
        <Default>my function</Default>
      </Literal>
    </
Declarations>
    <
Code Language="CSharp">
      <![CDATA[
           SqlConnection con = new SqlConnection();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "";
                cmd.Parameters.AddWithValue("", "");
                cmd.Parameters.AddWithValue("", "");
                cmd.Parameters.AddWithValue("", "");
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
 
                throw;
            }
            finally
            {
                con.Close();
            }
]]>
    </
Code>
  </
Snippet>
</
CodeSnippet>

Snippet IntelliSense

CodeSnpt4.gif

Snippet generated C# code

CodeSnpt5.gif
 

Up Next
    Ebook Download
    View all
    Learn
    View all