Monday, October 6, 2008

Snippets

You know how in Visual Studio you can type 'mbox', press Tab twice and Visual Studio will convert it into

MessageBox.Show("Test");

Or, you can type 'ctor', press Tab twice and the constructor for the class will be generated?

This can be customised. Have a look at the following file:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>props</Title>
<Shortcut>props</Shortcut>
<Description>Code snippet that checks for a null property</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>field</ID>
<ToolTip>backing store</ToolTip>
<Default>mProp</Default>
</Literal>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[private $type$ $field$;
public $type$ $property$
{
get
{
if (this.$field$ == null)
{
this.$field$ = new $type$();
}
return this.$field$;
}
set {this.$field$ = value;}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

You can now save it with any name you like, and then press Ctrl-K, B (or choose Tools -> Code snippets manager), press 'Import', navigate to this file and select it.

Now, if you type 'props' and press Tab twice, the system will convert it into the following little pattern for getting a private member through a property, with checking if it is null:

private int mProp;
public int MyProperty
{
get
{
if (this.mProp == null)
{
this.mProp = new int();
}
return this.mProp;
}
set {this.mProp = value;}
}

From here it's easy to understand how to make 'snippets' that do anything you want.

by . Also posted on my website

No comments: