Visual C# Code Snippets

What is a code snippet?

Code snippet is a ready made few lines of code, which is ready to insert into your code. Say you want to add a property to your class in C#. Type prop and press tab key twice, you will have a property inserted in your class which is waiting to be modified according to your requirement.

C# code snippets make day to day life of a C# programmer is very easy.

How to use code snippets?

Here is the link to default code snippets supported in Visual Studio: https://msdn.microsoft.com/en-us/library/z41h7fat.aspx

How to create a code snippet?

Steps to create your own method snippet is as follows.

1. Create a new text file and name it as method.snippet

2. Copy and paste the following code in to the method.snippet file.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>method</Title>
            <Shortcut>method</Shortcut>
            <Description>Code snippet for method</Description>           
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>methodname</ID>
                    <ToolTip>Method name</ToolTip>
                    <Function>MethodName()</Function>
                    <Default>MethodNamePlaceholder</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public void $methodname$ ()
    {
        $end$
    }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

3. Copy your file into visual studio’s snippet folder.

 My snippets folder located at : C:Program Files (x86)Microsoft Visual Studio 12.0VC#Snippets1033Visual C#

4. Restart visual studio if you have already running it.

5. Open visual studio C# class and type method and press tab key twice.

6. You will see a method created as follows

public void MethodNamePlaceholder()
    {

    }

7. Go ahead and change your method as you want.

Credits:

 http://stackoverflow.com/a/19247785/778101

https://msdn.microsoft.com/en-us/library/ms165394.aspx

have fun with code snippets!

Advertisements

Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s