Snippet in Visual Studio to create static method

Posted on June 27, 2007

After using Textmate for a couple of weeks I’ve come to realise how incredibly powerful and beautiful it is! Creating text snippets is a breeze – and improves productivity no end!

To achieve the same affect in Visual Studio though is a right pain in the butt-ocks. All I wanted to do was create a very basic snippet to define a static method (because I was creating a bunch of them all at the same time) and had to get down and dirty with some XML.

Anyhoo – here’s my result:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Public Static Method Declaration</Title>
      <Shortcut>pubs</Shortcut>
      <Description>Code snippet for creating a static method</Description>
      <Author>Chris O'Sullivan</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>return_type</ID>
          <ToolTip>Return Type</ToolTip>
          <Default>void</Default>
        </Literal>
        <Literal>
          <ID>method_name</ID>
          <ToolTip>Method Name</ToolTip>
          <Default>method</Default>
        </Literal>
        <Literal>
          <ID>param_type</ID>
          <ToolTip>Param Type</ToolTip>
          <Default>param_type</Default>
        </Literal>
        <Literal>
          <ID>param</ID>
          <ToolTip>Name of Param</ToolTip>
          <Default>param</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[public static $return_type$ $method_name$($param_type$ $param$)
            {
            }
          ]]>
        </Code>
      </Snippet>
    </CodeSnippet>
    </CodeSnippets>
Then you just type pubs[tab] and it will create a declation like this:
public static void method(param_type param)
{
}

With the ability to tab between the different fields.

But oh man what a pain that was to do! (I love you textmate – xx)