I was chatting with my pal Kelly at work last week about code snippets. This weekend, I had a pile of dirty dishes to clean, so I fired up my laptop and downloaded the archived DotNetRocks interview with Michael Palermo on code snippets. Before I knew it, the dishes were clean and I had refresher on code snippets!
I took a look at Palermo's site, www.gotcodesnippets.com. I was looking for some snippets I'd could install. I downloaded one that creates a property whose value is stored in the ASP.Net viewstate. I do that technique quite a bit, so it'll be fun to hit ctrl+k+x to run that snippet.
Next, I was interested in writing one by myself, just to see what it was like. I had downloaded the ternary code snippet, but I wasn't to warm and fuzzy about it. The snippet ought to have given me the opportunity to type in the variables using the special code snippet mode before reverting back to standard mode in Visual Studio. So, I grabbed their code, made a few changes and now creates a line of code with a ternary operator in it - just how I like. Here' the snippet that I dropped into my snippet folder.
Folder: \My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets
ternary.snippet XML File:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Ternary</Title>
<Shortcut>ter</Shortcut>
<Description>Custom code snippet for ternary operator</Description>
<Author>andrewdothay</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>result</ID>
<ToolTip>Replace with the field or property that will recieve the value</ToolTip>
<Default>result</Default>
</Literal>
<Literal>
<ID>expression</ID>
<ToolTip>Replace with the expression to compare</ToolTip>
<Default>expression</Default>
</Literal>
<Literal>
<ID>trueValue</ID>
<ToolTip>Replace with the value if the expression is true</ToolTip>
<Default>trueValue</Default>
</Literal>
<Literal>
<ID>falseValue</ID>
<ToolTip>Replace with the value if the expression is false</ToolTip>
<Default>falseValue</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[ $result$ = ( $expression$ ) ? $trueValue$ : $falseValue$;$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
This snippet uses four variables. The <Code> element contains placeholders for the line that will be emitted by the code snippet. The "$" symbol surrounds the variable so its easily identifiable by the snippet engine. When Visual Studio is in the special mode, I can tab between the variable fields to enter the value, then hit tab+tab to switch back to normal view after I've entered in the customizations. Sweet!
>>>>>>>>>>>>>>>>
I just found this four minute screencast on Channel 9 too! She does an excellent job of showing one up close.