So, a couple of days ago I discovered just how easy it is to create code snippets for Visual Studio 2005, and this apparently put me into snippet mode. My first attempt at code snippets unintentionally caught a bit of flak, so I hope this second one is less controversial.

Often, I find myself typing code like this:

MyClass mc = foo as MyClass;
if (mc != null)
{
    // Do something meaningful with mc here
}

It's not difficult, but when you've done it a couple of hundred times, it gets a bit tedious to type, so here's the astype code snippet:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>astype</Title>
            <Shortcut>astype</Shortcut>
            <Description>Code snippet for casting an object to a type and working on the casted instance.</Description>
            <Author>Mark Seemann</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>The destination type</ToolTip>
                    <Default>object</Default>
                </Literal>
                <Literal>
                    <ID>variable</ID>
                    <ToolTip>The name of the new variable.</ToolTip>
                    <Default>name</Default>
                </Literal>
                <Literal>
                    <ID>expressionToCast</ID>
                    <ToolTip>The expression to cast.</ToolTip>
                    <Default>expression</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[$type$ $variable$ = $expressionToCast$ as $type$;
    if ($variable$ != null)
    {
    }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Again, just paste this XML into a text file and save it to the C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# and begin using it by typing astype in the code editor.

If you don't care for the copying and pasting, I've also included the snippet file as an attachment to this post, so you can just dowload it to your C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# folder and start using it right away.