Visual Studio 2013: Organize Your Code with Named Regions

 

This feature was first introduced in Visual Studio 2005 and, over the years, I’ve heard plenty of arguments for and against using it. Those “against” think this can be used as a crutch to hide bad code and not adhere to good coding techniques. Those “for” think this is a great way to organize your code and get clutter out of the way. I’ll show you how it works and let you decide which group you fall into.

 

 

 

Creating Named Regions

 

C++

In C++ you create regions by using “#pragma region” with label and “#pragma endregion” (case-specific):

5-16-2012 12-21-15 PM

 

 

C#

For C# you can eliminate the “pragma” keyword, as well as the quotes around the region name if you desire, and just use “#region” with label and “#endregion” (case-specific):

5-16-2012 12-24-08 PM

 

 

VB

Visual Basic is just as easy as C# and uses a similar syntax of “#Region” with label and “#End Region” (not case-specific):

5-16-2012 12-26-57 PM 

Note that the quotes around the region name are required in this example.

 

 

 

Value of Named Regions

The value of creating Regions is twofold. First, they travel with the code so are shared by all team members when using source control. Second, they become part of document outlining and can be collapsed:

 5-16-2012 12-30-40 PM 

 

or expanded to further organize you code:

5-16-2012 12-29-04 PM

 

 

 

Best Practice

Special thanks to Marcus Rangell for reminding me of this tip. As a best practice you might consider putting the name of the region in the End Region line as well:

5-16-2012 9-00-45 PM

This technique will work with C++ and C# but not with VB regions.

 

The best practice is particularly useful when you have nested regions:

5-16-2012 9-22-04 PM

 

The only down side is this doubles up the names in C++ when regions are collapsed:

5-16-2012 9-24-18 PM

You will not see this problem in C#.