Why use regions in C #?

9

What are the advantages and disadvantages of using #regions in C# ?

Does your use really make it easier to organize your code?

#region

/* Código */

#endregion
    
asked by anonymous 17.03.2014 / 19:52

3 answers

12

It's irrefutable that regions make organizing easier, but care should be taken with what you really plan to organize.

I recommend using them when you have the following purposes in mind:

  • Group generated code;
  • Separate large code snippets;
  • Other readability purposes.

I believe that the use of regions to separate members of a class according to protection levels (private, public, etc) is justifiable, but I define their use as preferential since, the best thing to do is to group them according to their functionality, in others it becomes more feasible to organize them based on the needs of your application.

Now, using regions to hide "ugly" code is reprehensible; when the intention is to hide, why not avoid future confusions and spend a small part of the time in refactoring certain functionality?

    
17.03.2014 / 20:57
4

The idea is to decrease the amount of code displayed on the screen by grouping common functions. The advantage is to leave the code more succinct for reading.

The disadvantage is that the regions hide the signatures of the methods. When it is important to see the signatures of each method, the shortcut Ctrl + M , Ctrl + O .

    
17.03.2014 / 20:03
3

This is just a way to organize code, and is usually used by generated code.

In non-generated codes I recommend a certain care when using regions, because when used to separate codes according to any classification, they tend to get outdated.

  • For example, if you use regions to group private members, and someday some of them need to become public, I really bet the member will continue within the region.

The use I recommend is to group members who have some real connection. For example:

  • A static field, initialized only once, that serves a single method, could be placed within a region along with the method ... obviously I am in favor of a nomenclature that also indicates that this field is part of this method , so that other programmers know about it
17.03.2014 / 19:58