10

I really appreciate the possibility to define regions in your code, as it improves the readability insanely.

Anyways, I'd like to have everyone using the same convention in all classes (with the predefined order of all regions) like:

  • Private Fields
  • Constructors
  • Class Properties
  • Event Handlers
  • etc...

Do you have any proposition how this division could look like (What regions have sense and what names should they have) and in which order should they be defined ?

theSpyCry
  • 12,073
  • 28
  • 96
  • 152
  • 4
    This question may benefit from being flagged as "Community Wiki", as there is no single correct answer... – Rowland Shaw Apr 06 '10 at 08:18
  • 1
    The answer is simple: Realize that your basic assumption "as it improves readability" is indeed a false one. The answer then becomes "null" and you have greatly simplified your own life and especially all the poor chaps seeing it after. Regions are from hell. They cannot be automatically enforced/checked and they are therefore a huge factor in unreadable code. In the name of all that is holy and right in this world: Do. Not. Use. Them. – Casper Leon Nielsen Jan 11 '13 at 12:44
  • Its always easy said then done thing; I have worked on a lot of enterprise applications and more then 50% of the classes are more then few hundred lines of code, 20-30% or more having 100 lines of code. People advocating against regions start without regions and after few years end up having classes with hundreds of lines of code with spaghetti code, types scattered everywhere. – akjoshi Jul 30 '13 at 12:15
  • Thats controversial , some people say that regions are a bad style... – chriszero Apr 06 '10 at 08:15
  • Dupe: [any-standard-way-to-divide-a-class-into-regions](http://stackoverflow.com/questions/1476550/any-standard-way-to-divide-a-class-into-regions) – nawfal Feb 03 '14 at 09:03
  • As far as I know (I'm new at both programming and C#) regions are a recent addition to the language. Being that the case I think that the older programmers are more likely to complain about them. There's always resistance to adapting to the new. – carloswm85 Apr 07 '22 at 11:54

10 Answers10

37

My convention is not to use them.

If you find your class getting too big such that you need to hide vast parts of it through regions I propose your class is too complex and should be broken apart.

Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90
  • 2
    +1, http://www.google.com/search?q=c%23+regions+are+bad&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a – mxmissile Apr 06 '10 at 08:18
  • 2
    OK but let's presume that we have a simple WinForm which has about 20 EventHandlers in its code behind. Is really hiding them in this case pointless? – theSpyCry Apr 06 '10 at 08:32
  • 2
    @PaN1C_Showt1Me Well, that's what partial classes are for. – Jon Limjap Apr 06 '10 at 08:42
  • 2
    @PaN1C_Showt1Me - yes. You shouldn't have much else in your WinForm's code behind except event handlers and method calls within them to the actual workers. That shouldn't be too big. – Michael Shimmins Apr 06 '10 at 08:49
  • Thank you for stating the obvious! Regions are slightly less painful than hemorrhoids. – Casper Leon Nielsen Jan 11 '13 at 12:45
  • -1 A terrible generalization. Some very complex data transformations, e.g. file format conversions just require a lot of logic to achieve what is specified. Putting it in multiple files instead of one doesn't make it any easier to understand. If you can break something down naturally - sure, do that. If you can't break it down DO NOT FORCE IT - you will make it worse. – julx Sep 06 '20 at 19:30
13

Someone once said that having a convention like the one above:

  • Private Fields
  • Constructors
  • Class Properties
  • Event Handlers
  • etc...

is like setting a table where all the plates are together, all the spoons are together, all the knives are together and all the forks are together.

My take on the #region issue is to put related methods, event definitions, and properties together in one region. However, having to do this at all would indicate a code smell (either your class is too big or does too many things) but this is a good first step into refactoring it into a better class.

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
7

Whenever I see regions I think that the code is either generated or in need of re-factoring.

Avoid using them and when you feel the need for them, re-examine what you're doing and try to split your class in to smaller ones. Ultimately this will help with the readability of the application more than using regions will.

Keith Bloom
  • 2,391
  • 3
  • 18
  • 30
6

Personally I wouldn't recommend making code regions part of your code convention. The main reason being that regions hide code, which could potentially lead to issues like:

  • Developers might miss some important part of the source code
  • The average amount of LOC in the same file tends to increase

If you are interested in enforcing a coding style convention in your team, have a look at Microsoft StyleCop. Note that the tool currently only works for C#.

xmedeko
  • 7,336
  • 6
  • 55
  • 85
Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
4
#region Lotsa boring code and lookup tables

I use it to save screen real estate, nothing else :)

leppie
  • 115,091
  • 17
  • 196
  • 297
  • Your focus really shouldnt be on screen real estate as a programmer.. It should be on enforcable structure. Regions adds no value, it subtract value – Casper Leon Nielsen Jan 11 '13 at 12:53
4

I use the following regions:

Private Member Variables
Constructor
Public Properties
Private Methods
Public Methods
Events

The reason is because of better organization of code.
I work with files that may have over 2000 lines of code and it is very difficult to maintain the code without regions.

šljaker
  • 7,294
  • 14
  • 46
  • 80
  • 4
    "I work with files that may have over 2000 lines of code and it is very difficult to maintain the code without regions." Here's a suggestion. Don't work with files that have over 2000 lines of code. – Daniel Earwicker Apr 06 '10 at 09:38
  • 1
    May I know why I got downvote :) – šljaker Apr 06 '10 at 09:38
  • 2
    @Danel Earwicker, I work in a team that writes the information system for insurance companies. The project is very complicated and complex. I can not say "I will not work on this project until the files are not to be under 500 lines of code". :) There is a project manager who decides on everything, not me. I just gave an example. – šljaker Apr 06 '10 at 09:40
  • 3
    If you have a project manager who makes all your decisions for you, I guess my comment is for them to read. – Daniel Earwicker Apr 06 '10 at 11:05
  • Files with over 2000 lines of code? My god man - REFACTOR – Lawrence Tierney Mar 27 '15 at 11:39
3

I think there is no need in regions. Them are not legible. If you need (think, do you realy need?) an amount code in your class, you can use 'partial' class to split the class logic units.

Stremlenye
  • 585
  • 1
  • 3
  • 15
2

You might be interested in this do you say no to c# regions.

I think that so long as you're consistent accross your project it doesn't matter too much which order you write them in. Also be very very wary of overusing them (hence the initial link!).

There's nothing worse than finding a closed constructor region which is hiding only one line of code.

I think in the end it's down to personal taste. As I've said, consistency is the key!

Community
  • 1
  • 1
RYFN
  • 2,939
  • 1
  • 29
  • 40
  • 2
    Well I'd like to react on the post.. they say the good-designed code does not need regions. Anyways.. if you have 5 overloaded constructors - wouldn't it be easier for anyone opening that file.cs to see just 1 line 'Constructors' in place of 5 real constructors? – theSpyCry Apr 06 '10 at 08:21
  • I think the case you mention is certainly a good place to justify their use. I'm just wary of them as I've seen this carried from one place where they're useful into other places where they obscure code. – RYFN Apr 06 '10 at 08:57
  • The problem is they will never ever ever be consistent. Why? Because there is no way to enforce a given style and all conventions you make with regards to #regions are subject to rot from the onset. Regions are a tool used solely by amateurs OR to separate code in files where there is no other option. – Casper Leon Nielsen Jan 11 '13 at 12:46
2

Think of them as another form of comments: additional information mixed in with your code, which has no formal checking performed on it. Hence it will likely drift out of date with the code.

So NEVER duplicate in comments or region directives that which is already stated in the code.

Only add extra information.

In particular, using regions to restate the fact that certain members are properties, events, etc. is completely pointless. The most common problem there is that you create a region for "private methods", and then you edit one of them to make it public. Now you have to move it, which means that in a diff with the old version, the simple change is much harder to discern.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
2

I wrote my own region code snippet for VS 2008 which I always use:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
    <Header>
        <Title>#class region</Title>
        <Shortcut>#classregion</Shortcut>
        <Description>Code snippet for #region in classes</Description>
        <Author>Simon Linder</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>name</ID>
                <ToolTip>Region name</ToolTip>
                <Default>MyRegion</Default>
            </Literal>
        </Declarations>
        <Code Language="csharp">
            <![CDATA[#region Variables
                    $selected$ $end$
                #endregion

            #region Construction/Destruction
                    $selected$ $end$
                #endregion

            #region Properties
                    $selected$ $end$
                #endregion

            #region Public Methods 
                    $selected$ $end$
                #endregion

            #region Private/Proteced Methods
                    $selected$ $end$
                #endregion]]>
        </Code>
    </Snippet>
</CodeSnippet>

As you can see I do use regions for Variables, Construction/Destruction, Properties, Public and Private methods. I often add another sub-region into the private region called events. The order of regions also works fine with StyleCop.

Simon Linder
  • 3,378
  • 4
  • 32
  • 49