Introduction
This tip is aimed at creating custom code snippets in Visual Studio. The example shown applies to C# but can be extended to any language supported by Visual Studio.
Background
A bit of XML is preferred, but don't worry if you don't know how - it's not hard at all. (I don't know even a bit of XML!)
Using the Code
Snippets can be written in XML and can be made for any language in Visual Studio. Below is an example for code snippet for a property changed event handler method.
="1.0" ="utf-8"
<codesnippet format="1.0.0"
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>Notify Property Changed Method</Title>
<author>Akash</author>
<shortcut>npcm</shortcut>
<description>This method implements the
OnPropertyChanged method and binds to the event handler</description>
<snippettypes>
<snippettype>SurroundsWith</snippettype>
<snippettype>Expansion</snippettype>
</snippettypes>
</Header>
<snippet>
<code language="CSharp">
<![CDATA[]]>
</code>
</snippet>
</codesnippet>
In the <code>
block, you can specify the language you are creating the snippet for.
In the Header <shortcut>
tag defines what you need to type in the editor to activate the snippet.
All the code goes between the tags.
<![CDATA[]]>
This is the snippet for a Notifiable Property.
It has some differences when compared to the above one. This snippet allows you to enter custom data wherever necessary. For example, in the below snippet 'Type
' and 'Property
' can be replaced when the snippet is activated.
The beauty of this is that you only need to change any string
once and it changes in all parts of your snippet.
="1.0" ="utf-8"
<codesnippet format="1.0.0"
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>Notifiable Property</Title>
<author>Akash</author>
<shortcut>nprop</shortcut>
<description>Property With in Built Property Changed method implementation.</description>
<snippettypes>
<snippettype>SurroundsWith</snippettype>
<snippettype>Expansion</snippettype>
</snippettypes>
</Header>
<snippet>
<declarations>
<literal>
<id>Type</id>
<default>string</default>
</literal>
<literal>
<id>Property</id>
<default>PlaceHolder</default>
</literal>
</declarations>
<code language="CSharp">
<![CDATA[]]>
</code>
</snippet>
</codesnippet>
Final Steps
- Save the file with .snippet extension.
- Save it in C:\Users\{User Name}\Documents\Visual Studio {Version}\Code Snippets\{language}\.
- Restart the VS environment.
- Have fun using the shortcut using the "Shortcut " tag... Just remember you have your friend intellisense.
Points of Interest
This will accelerate your coding speed and if you are a serious developer, then it will clearly show effect on your projects progress speed.
History
- 2nd December, 2015: Initial version
I've uploaded my C# snippets in rar format, they are for MVVM. Feel free to use them.