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
In C++ you create regions by using “#pragma region” with label and “#pragma endregion” (case-specific):
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):
Visual Basic is just as easy as C# and uses a similar syntax of “#Region” with label and “#End Region” (not case-specific):
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:
or expanded to further organize you code:
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:
This technique will work with C++ and C# but not with VB regions.
The best practice is particularly useful when you have nested regions:
The only down side is this doubles up the names in C++ when regions are collapsed:
You will not see this problem in C#.