Creating a Visual Studio snippet for a C# property with the "public string" access modifier

By Steve Endow

When I’m coding in Visual Studio and defining properties for a class, the most frequent type I use is string. This is especially true for Dynamics GP projects where over 90% of my properties are strings.

Visual Studio’s “prop” snippet helps by auto-generating most of the property declaration. However, repeatedly specifying “string” for dozens of properties gets tiresome.

Typing “prop” and hitting tab twice creates a property line (an “automatically implemented property”).

The default data type, however, is “int.” So, I typically press TAB, type “string,” and then TAB again to input the property name.

To combat this inefficiency, I explored creating custom snippets in Visual Studio, a simple process I should have implemented long ago.

Snippet file locations vary, but on my system they’re at:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C#

I copied the “prop.snippet” file to my desktop and modified it.

The original prop.snippet is shown below:

prop prop Code snippet for an automatically implemented property Language Version: C# 3.0 or higher Microsoft Corporation

Expansion

type Property type int

property Property name MyProperty

public $type$ $property$ { get; set; }``$end$]]>

I modified the highlighted elements and deleted the lines marked in red, resulting in:

props props Code snippet for an automatically implemented property Language Version: C# 3.0 or higher Steve Endow

Expansion

type Property type int

property Property name MyProperty

public string $property$ { get; set; }``$end$]]>

To import your new snippet, go to Tools -> Code Snippets Manager -> Import. It is advisable to select only one category during import. For instance, use either My Snippets or C#, as selecting multiple categories may cause Intellisense to identify duplicate snippets with the same name.

UPDATE: While attempting this on a new Server 2012 machine, I encountered limited Location choices: “My Code Snippets” and “ASP.NET MVC 4,” without the option for “Visual C#.” This was resolved by launching Visual Studio 2012 as an administrator, which revealed the full list.

With my “props” snippet imported, I save a TAB keystroke and avoid typing “string” repeatedly. The code now directly inserts “string” and positions the cursor for the property name.

I encourage exploring custom snippets, especially if you frequently work with properties. While there are undoubtedly many other ways to utilize snippets effectively, this simple customization significantly reduces my typing effort.

Steve Endow is a Microsoft MVP for Dynamics GP and a Dynamics GP Certified IT Professional based in Los Angeles. He owns Precipio Services, a company specializing in Dynamics GP integrations, customizations, and automation solutions.

Connect with him on Google+ and Twitter

http://www.precipioservices.com

Licensed under CC BY-NC-SA 4.0