Creating Your Own Code Snippet

Datetime:2016-08-22 22:14:33          Topic: C#           Share

There is a good reference on the Microsoft site where you can go in details how to create all fields for snippets. But, I would like to get started with the basic script that I have created while working with Task Library.

Here is how you can implement it.

Observe the code below where I have added some code (you can modify the code to whatever you want.). Save this file with the .snippet file extension.

As you can see below, basically, the code snippet which we want to have in the code goes in CDATA block. (I would suggest you play around the syntax to get the exact format of the code).

<?xml version="1.0" encoding="utf-8"?>  
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">  
    <CodeSnippet Format="1.0.0">  
        <Header>  
            <Title>ntsk</Title>  
            <Shortcut>ntsk</Shortcut>  
            <Description>Code snippet for Task via Factory</Description>  
            <Author>Tapan Patel</Author>  
        </Header>  
        <Snippet>  
            <Code Language="csharp">  
<![CDATA[Task.Factory.StartNew(()=>  
{  
  
}  
);]]>  
</Code> </Snippet>  
    </CodeSnippet>  
</CodeSnippets>  

Once you save that file on the hard disk, go to Visual Studio and navigate to Tool -> Code Snippet Manager.

Here, you can add a folder if you have stored the snippet at a dedicated folder. Otherwiae, you can just import the snippet file as I did.

Once you launch the Snippet Manager, you should select C Sharp as a language if working with C#. Also note that the location shown below is the one where you will find your existing code snippets.

At the bottom of the page, you should see an option for importing the .snippet file. Click on that.

After that, navigate to the snippet file location and select the snippet file. Upon selection, it will ask you to check the appropriate snippet folder where you want to integrate (basically, referencing for future uses) your imported snippet.

Note that by default, you have "My Code Snippets" folder selected, which means it is going to copy the snippet file to that folder. So, if you select Visual C# along with "My Code Snippets", it is going to create two copies of that snippet. And, when you will try to utilize the snippet, it will ask you to select one out of the two copies.

So, I won’t do that. Instead, I will only select Visual C#. Select Visual C# and click on Finish ->Click OK.

You are all set.

Navigate to any .cs file just to test out the snippet.

You should see something, as shown below.

Tap twice and you should be able to see that code inserted.

Please leave your comments if you have any question or are facing any difficulty while setting up the snippet.





About List