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>