Code snippets in Visual Studio are very helpful when you have to type the same old code structure again and again. I found myself doing this on a recent project and decided to create a code snippet for it. I'm using Microsofts Composite Application Guidance (a.k.a. Prism) and the Model-View-ViewModel pattern (M-V-VM). My ViewModels implement commands that are hooked into from the Xaml View. The command type is DelegateCommand<T>, a class provided by the Composite WPF library that comes with Prism. Here's my snippet:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>DelegateCommand</Title>
<Shortcut>delcom</Shortcut>
<Author>Dave Kehring</Author>
<Description>Creates a Prism DelegateCommand.</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Imports>
<Import>
<Namespace>Microsoft.Practices.Composite.Wpf.Commands</Namespace>
</Import>
</Imports>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Parameter type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>name</ID>
<ToolTip>Command name</ToolTip>
<Default>MyCommand</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
DelegateCommand<$type$> _$name$Command;
public DelegateCommand<$type$> $name$Command
{
get
{
if (_$name$Command == null)
_$name$Command = new DelegateCommand<$type$>($name$, Can$name$);
return _$name$Command;
}
}
public bool Can$name$($type$ param)
{
}
public void $name$($type$ param)
{
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
This produces the following example property declaration:
DelegateCommand<object> _SaveCommand;
public DelegateCommand<object> SaveCommand
{
get
{
if (_SaveCommand == null)
_SaveCommand = new DelegateCommand<object>(Save, CanSave);
return _SaveCommand;
}
}
public bool CanSave(object param)
{
}
public void Save(object param)
{
}
The code snippet creates a private DelegateCommand member and a standard property declaration with only a getter. The command is lazy-initialized. The two methods stubs are called by the DelegateCommand during runtime execution.
To use this snippet, save it in a file with the .snippet extension into %\My Documents\Visual Studio 2008\Snippets\Visual C#\My Code Snippets. Then, in Visual Studio, you simply type "delcom" to run the snippet:

Hit Tab to insert the snippet code into the IDE. Then, you provide replacement values for the DelegateCommand's type value (this is the type of the parameter passed to the command methods) and the name of the command: