When it comes to keeping my code clean I’m a bit of stickler for using regions to help group my methods and properties. I will admit that I don’t always put these in when I’m in a hurry but when I do go back to my code to add these in I find it can take a considerable amount of time. One thing I’m surprised by is that Visual Studios doesn’t have a nice built in way for adding regions by simply highlighting the code you want to enclose in a region. I ended up doing some research and found some ways to deal with this.
Using Visual Studio macros
After a quick search online I found macros that do the job. I decided to use the macro found here: http://weblogs.asp.net/fbouma/archive/2003/06/23/9140.aspx but made some alterations. Besides enclosing groups of methods with regions I like to ensure that the region tags have a newline between them and the code they are enclosing. I’ve also removed some of the extra macros they had as I didn’t need them. To add this macro to your Visual Studios go into View–>Other Windows->Macro Explorer, right click on MyMacro’s and add a new macro called “Regions”. An editor for the macro should open, if not right click on the macro and select “Edit”. Copy the following code into the macro editor and save it:
Public Module Regions
Sub MakeRegion(ByVal regionName As String)
If selection.IsEmpty Then
As a quick test highlight some code and double click the MakeRegion macro. A window should appear asking you to enter a name for the region. Enter in a name and press ok. Your highlighted ode should be enclosed with a region tag and have the name you entered beside the tag.
Using an Item Template with predefined Regions
A lot of times I find that I’m always creating the same regions; “Public Properties”, “Constructors”, “Public Methods”, and so on. Rather than having to manually create these all the time I decided to create an item template of a simple class file that already has these regions in it. This way they are there when I create the file and I can either remove them if I don’t need them or just leave them for future code. I’ve tested this with VS 2008 and 2010. It should work with VS 2005 too. To get this template working for you do the following:
1) Download template here: https://cid-e7dba9a4bfd458c5.office.live.com/viewpermissions.aspx/General%20Development/ClassRegionTemplate.zip?ref=11
2) Leave file zipped and copy it to C:\…\Visual Studio 20XX\Templates\ItemTemplates\Visual C#
3) Restart the version of Visual Studios you added this to and either create a new project or open an existing on. When you add a new item to your project you select “Visual C#”. You should see a template called “C# Class with Regions”
If you select this file type and call it “TestClass.cs” you will end up with something like this:
#region Public Proeprties
#region Public Methods
#region Private Methods