HomeSearch

C# Region and endregion

Use the #region and #endregion directives to help organize code blocks.
Region. The #region directive partitions your code. With #region, we can organize code into blocks that can be expanded or collapsed visually.
Syntax notes. We must indicate the start of the region and the end of the region. Two separate directives, region and endregion, are used for this purpose.Directives
In this example, we demonstrate some common usages of the #region directive. Please pay attention to the #region and #endregion directives. These are balanced throughout the source file.

Tip: You can optionally specify an identifier for the region, such as with #region FIELDS.

And: When you compile this program, the #region directives do not affect the intermediate language output.

Console
C# program that uses region directives using System; #region class Example { } #endregion class Program { #region FIELDS int _field1; int _field2; #endregion static void Main() { #region BODY Console.WriteLine("Hello world!"); Console.WriteLine("How are you today?"); #endregion } } Output Hello world! How are you today?
Example screenshot. In the code example, we see the complete program. In the screenshot, we see the code in Visual Studio environment with the #region areas collapsed.

Tip: To collapse a region, click the plus-minus sign on the left margin of Visual Studio next to your code.

A discussion. Region is not ideal. Consider instead using more classes and scopes. This enables compile-time detection of problems. It helps use the full capabilities of the C# language.Compile-Time Error
A summary. The #region directive operates at the level of the text. It does not require any particular scope to be balanced in the file. Regions do not affect the final compiled metadata.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls