Monday, March 31, 2008

VS Snippet: On-demand getter

I often use base page classes in my web apps. On these classes I put read-only properties for access to business layer classes. I typically set these getters up to do on-demand (or "lazy" instantiation) because not all pages will use the various business class instances that are available. Instead of creating them all on class construction or page load, the get created as needed. After figuring out how to fix the "prop" shortcut to work the way I needed, I realized it made sense to create a snippet for on-demand properties. Now I simply type "propod" and I get this:

private object myVar;

public object MyProperty
{
get
{
if(myVar == null)
{
myVar = new object();
}
return myVar;
}
}

Here's a Visual Studio shortcut snippet file XML for it. Just save it to a .snippet file in your visual studio snippets directory (i.e. C:\Program Files\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#):

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propod</Title>
<Shortcut>propod</Shortcut>
<Description>Code snippet for on-demand read-only
property and backing field.</Description>
<Author>Peter Lanoie</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>object</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[private $type$ $field$;

public $type$ $property$
{
get
{
if($field$ == null)
{
$field$ = new $type$();
}
return $field$;
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

3 comments:

Rob said...

Hi Peter,

Great to see you posting on Snippets, the more I get into these, the more I love them! I am slowly trying to build myself a little library of them (may post them in my blog too http://tinyurl.com/yt289e.

Do you use a tool for editing of snippets? I use "snippy" (http://tinyurl.com/35kbf9)and find it a great, lightweight app!

Be happy to trade some if interested!

Peter Lanoie said...

I just use the XML editor in Visual Studio. The snippet XML seems simple enough to just edit manually.

Anonymous said...

You may also want to take a look at CodeRush from DevExpress.

It does these kind of things, but offers you many more combinations as it's fully template driven. It's well worth the money....

Imar