Steps to create a C# Code Snippet
- Open in a text editor a file with the .snippet extension, (in listing 1 you can see a sample snippet code).
- Add the title to show and the Description in the propper element.
- Add the Shortcut and the snippet type.
- In the Snippet tree, add the namespaces to import.
- Next, add the Declarations (variables name and type), a tooltip to show and the default value, all these settings in a Literal element, one per variable.
- The last thing to do is to add the code to show when the snippet is inserted in the code file. In the Code element, add a Language and a Kind attributes.
- Next put inside a <![CDATA[ ... ]]> tag the code to show.
- And that's all!!!
If we use the snippet shown in the source code listing 1, we'll see it as shown in figure 1.
Figure 1. The sample snippet in action.
<?xml version="1.0" encoding="UTF-8"?>
<CodeSnippets xmlns="http:"//schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Random Number</Title>
<Author>Microsoft Corporation</Author>
<Description>Generates a random integer between an upper bound and a lower bound.</Description>
<Shortcut>mathrandom</Shortcut>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Imports>
<Import>
<Namespace>System</Namespace>
</Import>
</Imports>
<Declarations>
<Literal>
<ID>LowerBound</ID>
<Type>int</Type>
<ToolTip>Replace with the smallest integer you want in the result set.</ToolTip>
<Default>1</Default>
</Literal>
<Literal>
<ID>UpperBound</ID>
<Type>int</Type>
<ToolTip>Replace with one more than the largest number you want in the result set.</ToolTip>
<Default>6</Default>
</Literal>
</Declarations>
<Code Language="csharp" Kind="method body"><![CDATA[Random generator = new Random();
int randomValue;
// Generates numbers between 1 and 5, inclusive.
randomValue = generator.Next($LowerBound$, $UpperBound$);
]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Related links:
How to install a C# code snippet
|