:: KBs ::

Regions in Code

Created Date: 4/23/2008
Last Modified Date: 4/23/2008
One of the items that rarely seen properly executed is code regions. A region is effectively a way of taking code and segmenting it into smaller blocks. There are many different ways that it could be used. Two different structures seem to make the most sense.

1.   (C# / VB.Net) Region all of the different types of components together.

Example

public class TestClass
{
   #region Constants
   #endregion
   
   #region Variables
   private String _Value1;
   private String _Value2;
   #endregion
   
   
   #region Properties
   public String Value1
   {
      get
      {
         return _Value1;
      }
      set
      {
         _Value1 = value;
      }
   }
   
   public String Value2
   {
      get
      {
         return _Value2;
      }
      set
      {
         _Value2 = value;
      }
   }
   #endregion
   
   #region Constructors
   public TestClass()
   {
      _Value1 = String.Empty;
      _Value2 = String.Empty;
   }
   
   public TestClass(String Value1)
   {
      _Value1 = Value1;
      _Value2 = String.Empty;
   }
   #endregion
   
   #region Methods
   #region Public Methods
   public String GetValues()
   {
      return String.Concat(_Value1, _Value2);
   }
   #endregion
   
   #region Internal Methods
   #endregion
   
   #region Protected Methods
   #endregion
   
   #region Private Methods
   #endregion
   #endregion
}

2.   (C# only) Region code that should be used is for extracting items that are related. This is an excellent technique for locating items that could be refactored in the long term.

public int GetDifference()
{
   #region A code
   int A = _A++;
   A *= 3;
   #endregion
   
   #region B code
   int B = _B--;
   B /= 4;
   #endregion
   
   return A - B;
}
:: Better Coding Practices ::