Simple Walkthrough on Visual Studio Code Snippets

 

I guess most of the Software Developers might have used or aware of the Code Snippet feature in Visual Studio which helps us to write code much faster. Did any of us try to explore how Code Snippets work or in other words how the shortcut gets converted to extensive code?

Let’s explore in this post how Code Snippet work and try to see where the code is defined for a particular Code Snippet.

Exploring Existing Code Snippets

First lets try to see all the existing snippets which comes by default in Visual Studio. This can be seen by opening the Code Snippets Manager by invoking the shortcut key(CTRL + K,CTRL +  B) or go to Tools -> Code Snippets Manager as shown in the figure below:

Code Snippet Manager

Once the Code Snippets Manager comes up, it will list down the available Code Snippets which are preloaded with the manager as shown below:

Code Snippets Manager dialog box


Locating Code Snippet File

To Understand the structure of the Code Snippet let us try to see a simple code snippet which is already defined for Visual C#.

To do that select Language as CSharp in the Code Snippets Manager and in the list box expand the Visual C# section. We will try to see the Snippet definition for class Snippet.

Click on the class Snippet and you will see the information associated with the snippet. To see where the snippet is stored go to the location field and navigate to the snippet file specified in the location.

Open the Snippet file in Notepad and you will be able to see the XML formatted snippet definition which also contains the snippet code as shown in the figure below:

Code Snippet Definition File


Understanding Snippet File Structure

As you can see that the snippet file extension is .snippet.

It’s basically structured as XML with custom Attributes. There are two main components for a Code Snippet. One is the Header Tag and the other one is the Snippet Tag.

Header Tag defines the Metadata associated with the code snippet such as Title, Shortcut, Author etc.

While the Snippet Tag defines the functionality of a code snippet or in other words structure of the code snippet. Code Tag defines the code associated with the snippet and the variables used in the Code is declared under the Declarations Tag. It is the code portion which replaces the snippet shortcut in the Visual Studio Editor.


Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Step By Step Guide to Detect Heap Corruption in Windows Easily

How to dynamically add Properties in C# .NET?