Creating your own Visual Studio code snippets


<re-published from my old blog> 


Some time back I got thinking... everytime I start reading mails in the C# discussion alias at my company or Eric Lippert's explanations of why the supposedly peculiar behaviour is in fact logical... the first thing I do is open up my very extensively used "ExperimentalConsoleApplication" solution in Visual Studio, comment out the existing main function in the console app project 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

Skip to main content