Home c# How to use #region and #endregion directives in C #

How to use #region and #endregion directives in C #

Author

Date

Category

I’ve read about #region and #endregion that they are needed for grouping class members, but I couldn’t find it in more detail. I want to understand in more detail.


Answer 1, authority 100%

The #region directive allows you to specify a block of code that can
expand and collapse using the structuring function in
Visual Studio code editor. In large code files it is very convenient
collapse or hide one or more areas to avoid
distract attention from the part of the file that is currently above
work is in progress.

Example

# region MyClass definition
public class MyClass
{
  static void Main ()
  {
  }
}
#endregion

Source


Answer 2, authority 97%

Imagine you have a class that inherits multiple interfaces.

You implement all the necessary methods, while grouping them using regions.

This is perhaps the most typical case that is implied when talking about grouping using regions.

The second typical example is hiding nested classes in regions.

public class MyClass: IFoo, IBar
{
  # region [IFoo implementation]
  public void Foo1 ()
  {
    throw new System.NotImplementedException ();
  }
  public void Foo2 ()
{
    throw new System.NotImplementedException ();
  }
  public void Foo3 ()
  {
    throw new System.NotImplementedException ();
  }
  #endregion
  #region [IBar implementation]
  public int Bar1 ()
  {
    throw new System.NotImplementedException ();
  }
  public string Bar2 ()
  {
    throw new System.NotImplementedException ();
  }
  #endregion
}
public interface IFoo
{
  void Foo1 ();
  void Foo2 ();
  void Foo3 ();
}
public interface IBar
{
  int Bar1 ();
  string Bar2 ();
}

Answer 3, authority 94%

I often use #region to hide large chunks of boilerplate code. A good example is the WPF dependency property implementation. Such a lot of code:

# region dependency property FieldValue Value
public FieldValue Value
{
  get {return (FieldValue) GetValue (ValueProperty); }
  set {SetValue (ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
  DependencyProperty.Register ("Value", typeof (FieldValue), typeof (SingleField));
#endregion

is actually completely redundant, so it makes sense to collapse it so as not to waste time on it, and see only

[dependency property FieldValue Value]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions