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
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="">
<CodeSnippet Format="1.0.0">
<Description>Code snippet for on-demand read-only
property and backing field.</Description>
<Author>Peter Lanoie</Author>
<ToolTip>Property type</ToolTip>
<ToolTip>Property name</ToolTip>
<ToolTip>The variable backing this property</ToolTip>
<Code Language="csharp">
<![CDATA[private $type$ $field$;

public $type$ $property$
if($field$ == null)
$field$ = new $type$();
return $field$;


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

Do you use a tool for editing of snippets? I use "snippy" ( 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.

Imar Spaanjaars 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....