How to create your own code snippet and use it in visual studio?

Nuthan Murarysetty
3 min readAug 22, 2021

--

Create your own code snippet in visual studio

First of all why Code snippet?

Code snippets help to save developers time. Do you think how? Let me explain with an example.

In real-time, we often use logging-in programming to know if any issues or necessary information we use to keep for future reference.

Ex: logger.LogError(“ErrorMessage”);

Note: This is just an example and gives you an idea and creates it on your own for any code to convert into a snippet.
You can create a code snippet for C#/Html and many more languages. Any statement you can configure.

Using this approach you can just type the shortcut in the visual studio editor and press the tab twice.

Now you can see your actual statement of what you configured in the code snippet file. Replace the placeholder with actual text.

Extension for a code snippet: .snippet

Ex: I am going to show you a simple Console.ReadLine() code snippet and file name which I create as ReadLine.snippet

Sample XML snippet file which we have for Console.ReadLine():

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Console Read Line</Title>
<Author>Nani</Author>
<Description>Creates a shortcut for Console.ReadLine()</Description>
<Shortcut>cr</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[Console.ReadLine();]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Now, we should learn how to import this .snippet file into visual studio,

Go to Tools => Code Snippet Manager

Click on Import => Choose your snippet file from the location

Click on Open and choose the folder where you want to place this snippet

Click on Finish and finally click OK.

Now it's our turn to check our code snippet in the code editor

After you type cr and then press the tab twice then it will show the actual statement like the below,

I hope this quick article helps you understand the purpose and how it reflects in our day-to-day work. So, Why late? prepare your list of code snippets and use it in just two tab clicks.

Happy learning :)

--

--

Nuthan Murarysetty
Nuthan Murarysetty

Written by Nuthan Murarysetty

I love sharing things what I know to others and passionate in photography.

No responses yet