What is a Code Region?
Visual Studio allows the creation of code regions within the code of a program or class library. A code region is simply a named section of code that can be hidden from view as required. This allows areas of code to be organised. Code regions only affect the manner in which source code is displayed. Adding one or more regions has no effect on the final, compiled software.
The #region Preprocessor Directive
The C# compiler recognises various preprocessor directives. These are commands that are interpreted during the compilation of the program that may affect the compiler's final output. They can also be used to modify the way that code is displayed in the integrated development environment (IDE). Preprocessor directives are identified by a leading "hash" symbol (#). Two directives are used for code regions. The first identifies the start of the region and includes the "#region" command and the name of the region being defined. The second, "#endregion" denotes the end of the code region.
When a code region is created, Visual Studio automatically places a minus symbol (-) in the margin near the region and a line terminating at the end of the region. This is the area that the IDE has identified as a region. The image below shows an example region:
The minus symbol in the margin can be clicked to collapse the code region. Once collapsed, the minus is replaced with a plus symbol (+) that can be clicked to expand the code again.
Considerations
Code regions can be very useful for organising code. However, care should be taken to ensure that code is hidden sensibly. It is possible to hide very small areas with a method. This can lead to the code becoming difficult to read or even misleading when the regions are collapsed.
Other Code Regions
Visual Studio automatically generates regions for namespaces, classes, methods and other code structures. No preprocessor directives are used in these cases. The IDE simply creates the controls in the margin to collapse and expand these areas.
19 February 2008