C# Programming > Miscellaneous

C# Code Region

Region Code Formatting

C# Code Regions are something offered by versions of Visual Studio to help developers. Code regions are a way to organize and format source code and have no impact on final applications.

Although some programmers do not like regions, they are useful and make coding more efficient when used properly.

Declaring Region Blocks

Even though code formatting regions are not part of the .NET language, Visual Studio treats them like keywords. The keywords you need to know are #region and #endregion. As expected, any source code in between those two tags will be considered part of the region block.

Conviniently region blocks can be located within other code region blocks. If fact you can have as many nested source code regions as you want, although like all things, nesting is best in moderation.

So what happens when a block of source code is in a region? Visual Studio lets you "hide" that particular block of code:

c# code region

Regions can hide pages of C# source code or they can hide a single .NET function. This is the part that many developers do not like. Code regions give developers the ability to potentially create a false sense of organization in source code. However that does not mean that regions can't be useful when used responsibly to create segments within a file of source code.

Other developers complain about the fact that regions make it uneccesarily tedious to read through a file of code. According to them, hiding code reduces the readability of the program as a whole. While that is true, reading excessively long files of .NET source code also makes it difficult to understand. It is a balance. The point is to format source code to make it easier to read.

Code Formatting Shortcuts

Since C# code regions as part of a toolset to format .NET source code, they come with keyboard shortcuts to make life simpler:

Ctrl+M, Ctrl+M expands/collapses the current region block.
Ctrl+M, Ctrl+O collapses all the region blocks in the current source code file.
Ctrl+M, Ctrl+L has the opposite effect, expanding all .NET code regions.

Using those three keyboard shortcuts, developers can take full advantage of formatting code with region blocks.

Back to C# Article List