If you haven’t been programming in visual studio for long, chances are you haven’t heard about code snippets.

A code snippet is actually coding that you can quickly insert into the code editor. Typically, snippets are common language constructs you use often, and many come bundled with Visual Studio. You probably noticed them in IntelliSense as you were typing code.

Code snippet for try/finally

You can go to the code snippet and then hit the TAB key twice to insert it.

Some useful C# snippets are:

  • #region – Inserts #region and #endregion, puts a cursor where you would normally type the name.
  • try – Inserts a try-catch
  • tryf – Inserts a try-finally
  • for and forr – Insert for and reverse for loops
  • prop – Inserts an automatic property
  • propfull – Inserts a property and a backing field

As snippets for these short constructs exist, there are also snippets for entire classes and methods. And you can also create your own. To see all snippets that are shipped with Visual Studio, simply go to Tools –> Code Snippets Manager…

Getting to the Code Snippets Manager

This nifty little thing is also available in Visual Studio Community Edition. You can play with the snippets, download new ones from the Internet and if you try to get into a habit of using them, possibly even improve your coding practices.

In a future blog post, we’ll create a small code snippet of our own. Happy coding!