They are used to group related sections of code so that multiple lines can be collapsed into a single line.
The best way to group is debatable. Many people (myself included) use the following groups (plus others)
Constants
Events
Fields
Constructors
Properties
Methods
Others group items that relate to each other e.g.
A field
The property that exposes the field
The event that is raised when the field is changed.
A combination of these can be used by nesting regions. Here's a full class that has a comprehebsive implementation of an int -
cool
. Without regions, with many fields/properties it can be hard to locate the correct regions in code. Now all Cool stuff is in one region, and nested regions for multiple methods etc.
public class MyClass
{
#region Cool Stuff
#region Cool Constants
public const int CoolMin = 0;
public const int CoolMax = 100;
#endregion
public event EventHandler CoolChanged;
private int cool;
public int Cool
{
get { return cool; }
set
{
if (cool != value)
{
if (CoolValidation(value))
{
cool = value;
OnCoolChanged(EventArgs.Empty);
}
else
throw new ArgumentOutOfRangeException(
"Cool",
string.Format("Cool must be between {0} and {1} inclusive", CoolMin, CoolMax));
}
}
}
#region Cool Methods
private static bool CoolValidation(int cool)
{
return cool >= CoolMin && cool <= CoolMax;
}
protected virtual void OnCoolChanged(EventArgs e)
{
EventHandler eh = CoolChanged;
if (eh != null)
eh(this, e);
}
#endregion
#endregion
}