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:
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!
I just use the XML editor in Visual Studio. The snippet XML seems simple enough to just edit manually.
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
Post a Comment