Creating your own Visual Studio code snippets

by robotix1986 19. July 2009 11:44

So just some time back I got thinking... everytime I start reading mails in the C# discussion alias at my company or Eric Lippert's explanations in them... the first thing I do is open up my very extensively used Console Application project in Visual Studio, comment out the existing main function for future reference and start writing a new one... and it is kind of a pain to do this.. so I thought that it's time to get it automated.. so I wrote a snippet to do that for me.

Below is the code for that: -

<?

xml version="1.0" encoding="utf-8" ?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <
CodeSnippet Format="1.0.0">
        <
Header>
            <
Title>mainfn</Title>
            <
Shortcut>mainfn</Shortcut>
            <
Description>Code snippet for 'Main' function</Description>
            <
Author>Alvaro Rahul Dias</Author>
            <
SnippetTypes>
                <
SnippetType>Expansion</SnippetType>
                <
SnippetType>SurroundsWith</SnippetType>
            </
SnippetTypes>
        </
Header>
        <
Snippet>
            <
Declarations>
                <
Literal>
                    <
ID>expression</ID>
                    <
ToolTip>Code in main method</ToolTip>
                    <
Default>Console.WriteLine("Hello World!");</Default>
                </
Literal>
            </
Declarations>
            <
Code Language="csharp"><![CDATA[ public class MyClass
            {
                public static void Main()
                {
                    $expression$
                    $selected$ $end$
                }
            }
]]>
            </
Code>
        </
Snippet>
    </
CodeSnippet>
</
CodeSnippets>


Most of the fields above are self explanatory. I'll explain a few important ones.
The <Shortcut> tag specifies what you need to type in VS to use this snippet.
<SnippetTypes> - where you can use this snippet, Expansion, Surround With or both.
<Code Language="csharp"> - the actual code to be inserted

Interesting thing to note is that all the variable items are marked with $ signs. The $selected$ attribute signifies where the selected code should go in case you use this code as a sorround with snippet.
The $end$ attribute signifies where the cursor should go once you're finished with the snippet.

Hope the above helps in your coding adventures.


Regards,
AlD

Tags: , ,

.NET

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About robotix1986

Yet another software developer in the software industry writing some kewl code and exploring new technologies when not doing the routine work stuff.

RecentComments

Comment RSS
Software Blogs - BlogCatalog Blog Directory