Sept. 21, 2006, 6:45 p.m.
IT

Why #region is evil in C#

C# has a nice preprocessor directive called #region. In principle it is very cool, but it is like so many cool ideas - HORRIBLY broken.

The idea behind the directive is to allow you (or the IDE) to mark a block of code for hiding in the IDE. So if I have:

#region Private members
private void SomeMethod() {
  int i;
  ...
}
#endregion

The editor will then allow me to use cold folding on that block and thus collapse it to:

Private members

I think the core motivation behind this was to allow the auto generated code in forms to be hidden - i.e. the Initialisation block for creating form controls. For this purpose I think the idea works sort of ok. But here is the catch. Give this feature to an inexperienced (junior/lazy) programmer, and chaos will erupt. Instead of using proper OO techniques (why did M$ not use proper OO encapsulation from the start), those developers write methods literally thousands of lines of code long and make it more manageable by wrapping some blocks in #region directives. THIS IS CRAZY! Why not refactor the logic into METHODS - yes, for the past couple of decades we have a nice feature called METHODS (procedures/functions/etc). It is sad - a good intention on Microsoft's side but one that can be abused so badly that maintainability goes out of the door. And by the way if you were wondering, in my humble opinion writing maintainable code for any project that has even the remotest kind of lifetime is much more important than anything else. There can be some bugs when you go live, there can be some stability issues - even security issues. All these can be quickly investigated afterwards and resolved. However, unmaintainable code will impede these activities AND make growing the product impractical and COSTLY.