share
Stack OverflowDo you say No to C# Regions?
[+216] [49] Dhana
[2009-04-16 10:12:06]
[ c# ]
[ http://stackoverflow.com/questions/755465/do-you-say-no-to-c-regions ] [DELETED]

The idea behind the question is - Just say No! to C# Regions [1]

It is said that "the reason to use #region tags because all the things they are hiding is just really bad code."

How do you use regions effectively?

(77) So not using regions equals better code? It's not like the bad code is going to go away. In a big project, there are better places to "hide" code. That blog post is just too naive. - Jabe
(1) Wow, seen some really unexpected answers here. I'll be sure to add this topic to future interview questions! - Andrew Bullock
(5) Who would have thought that a seemingly harmless topic such as regions can lead to such a heated discussion? :-) - Adrian Grigore
(2) The responses are awesome!!!! - Dhana
(1) Andrew how are you going to use them in interview questions? If I say I like regions in the interview is that an automatic round file? - Dining Philanderer
This has got to be the "Question of the day!" - Cerebrus
@Jabe: Well said. The ostrich mentality of using Regions to hide bad code is really stupid! - Cerebrus
@Dining Lol no. To me inappropriate region use is a code smell, indicating a need to refactor. My point here would be to see what their opinion would be for/against using them and whether or not it indicates a refactor candidate - Andrew Bullock
(1) there should be a new category for mega-subjective or something.. - RobS
If you don't like #regions but have to deal with them, checkout this answer for a Visual Studio extension to make #regions less painful: stackoverflow.com/questions/858132/… - NotDan
(22) The author of the article starts out by making an assertion that "regions are used to hide bad code". Then bases his entire argument as if his assertion were fact. How about using regions to hide the good/trusted/solid code so the dodgy code is more visible? It's fascinating how so many people take a stance that "it's not my way, so it must be wrong", and even manage to fool themselves with their own flawed arguments. - Craig Young
(1) Craig Young (above my comment) took the words out of my mouth. The author's making assumptions, write about them and expands while he's just being wrong from the start. I completely disagree with that article. - MasterMastic
(1) It seems like a lot of people dislike regions because they are used to hide "bad code." I have never really come across this though, could someone provide an example of regions being used this way? Maybe, a link to an open source project? As I see it, regions are useful because they help in improving readability (when used to group by functionality). - Tejas Sharma
[+439] [2009-04-16 11:16:15] TJB [ACCEPTED]

Three categories of uses for #regions:

1. Perfectly reasonable and downright helpful uses of #regions, for example:

  • Long variable definitions, e.g. some long string of bytes you have hard coded in your source
  • Designer generated code
  • Some embedded documentation or history, see old source control that appends history to the top/bottom of the file

Basically, in practice you may have to include some ugly artifact in your code depending on some tool or some strange requirement which is helpful or needed for some reason, but its not something you want to scroll over all the time. So you compromise by keeping it in your code but stashing it away so its not in your face.

2. Illegal uses of #regions punishable by WTFs such as:

  • Hide 'ugly code'
  • Copy and paste big chunks of code around (ever heard of a subroutine?)
  • Hide malicious or back-door code that lazy reviewers don't ask about.

3. Then, there are uses that depend on your preference, such as:

  • Using it to group members with related functionality
  • Using it to group types of class members (private, public, methods, properties, etc.)

This is a preference, but I believe that it is much more useful to group members by relationship or functionality rather than simply their type.

For example, grouping constructors may make sense because they all perform a similar function and may very well call each other, therefore it may be helpful to group them in a #constructors region. Whereas, you could have several private methods that do all kinds of different functions, some serving one set of properties, some serving the constructors. Therefore, just the fact that they are private methods does not imply that they are strongly related or that they should be grouped. Maybe they could instead be grouped by what kinds of application specific functions they perform. Maybe some are dedicated to order submission and others are dedicated to data conversion.

As developers, we naturally like to group things by type, but we have to remember that it is sometimes more helpful to group things by some functional relation instead.

But, as I said, this last group is largely up to preference, and heavily depends on the type of application and also your mood.

Also, don't forget there are other ways to organize your code such as partial classes or further refactoring of a class into multiple modules.

tl;dr Go ahead, use #regions!


(58) + Great Answer! This makes much more sense than flame-war'ing about whether or not #regions are evil. Another suggstion for category 3: Grouping code by functionality. (e.g. I sometimes use #regions to group MouseMove/Up/Down event handlers, they just "belong together") - Niki
(3) +1 for nuanced answer - Tormod Fjeldskår
@Niki, Thanx, I kind of implied that in the explanation after #3, but I don't know why i didn't include it as a bullet point! I agree. - TJB
(66) IMHO this should have been the accepted answer - RobS
I use them for grouping all properties together in one lump (i work in data access level a lot) and the rest of the methods are fine in a sensible order (by function groupings or name or access level), which ever makes more sense for the class. - Pondidum
(3) THIS is what the accepted answer to this question should have been. - galaktor
(1) Thanks all for the nice comments, good to see people are being open minded. - TJB
Love your answer and agree with you. - SoMoS
@rob: let all the thinking people downvote ((that answer)) (stackoverflow.com/questions/755465/do-you-say-no-to-c-regions/…) to Hades! or something of that nature. - bobobobo
(3) One other legitimate use IMO is as a temporary help in refactoring legacy code. When you're looking at a 300-500 line function that has dependencies scattered throughout it and you need to break it up into understandable chunks without destroying any meaning, regions are a nice solution. After you're done documenting and collapsing each bit of code, you can see the big picture and start planning your refactoring. (Then take them out, of course) - Michael La Voie
I use regions all the time, to group the code together, public/private/protected methods/properties/member variables. And within them, or if its a major section of functionality mixed between them, I group in the functionality, i.e. reading data and methods used in threads for reading data. The flamewars over regions do nothing but make me think is it wrong to use them, what harm can they do? - JonWillis
I find regions useful for preventing "code front bloat" such as having a region for private internal structs and classes. I don't think this is truly code hiding in the way, say, monkey patching or operator overloading is because the comment line is clerly visible as is the fact that it contains code that can be expanded. As in many features, the key is not to fall in love with it and use it everywhere and to clearly document what you are doing. - user430788
I use regiosn for one more, related reason. They are great for just showing the code I am currently talking about during lectures. - user430788
A lot of region-hating should be because users don't know how to quickly fold and unfold regions. Making use of shortcuts Ctrl M M, Ctrl M O, Ctrl M L etc makes it so easy. Regions or not, I always collapse methods and properties so that navigation by mouse is easier. - nawfal
I'm here to give a +1 and chew bubblegum. And I'm all out of bubblegum. Great answer. There are cases and cases where #regions can be used. And like @user430788 said, they are really good for lectures. - Hugo Rocha
1
[+139] [2009-04-16 10:16:16] Andrew Bullock

Absolutely an unresounding yes.

Its a little known fact that regions were actually added to the C# language by Satan himself.

Edit: The only excuse for using them is to hide designer generated code. Using them to group methods/properties by protection level is the most infuriating thing, ever! It achieves absolutely nothing but confusion. If you have THAT MUCH code in a single file, you need to refactor. SRP [1] anyone?

[1] http://en.wikipedia.org/wiki/Single_responsibility_principle

(30) The dreaded feature request nr 666 ;-). - Toon Krijthe
#region Cocytus ;) - Guffa
(1) I assume you disable code outlining then? This allows you to ignore them. - Richard
(3) No, my development team just writes sensible, clear, well factored code in the first place. - Andrew Bullock
(1) Is 500 lines too much? - Chris S
(6) of what, where? coke? probably. code inside a branch or method? yes, in a class? probably not. If you abide by this, you cant go wrong en.wikipedia.org/wiki/Single_responsibility_principle - Andrew Bullock
(3) I don't use them because I don't use them consistently, and nothing is always better than sometimes one way, sometimes another. It doesn't bother me terribly when others use them reasonably, though. I'm not a big fan of the religious-war nature of #region debates. - Greg D
Yes high cohesion, so breaking a source file (not a 200 liner, longer) into 4 distinct parts isn't really that evil. Small source files is pointless - Chris S
What I'm saying is over-regioning is bad (private,protected etc), minimal regioning helps in my view - Chris S
(1) Nowadays there are partial classes for designer generated code. Way more maintainable, IMO. - Tom Lokhorst
@Andrew: I assume your development team does not work on complex, not-so-sensible projects? Ever met clear, well-factored classes with 30 properties or more? - Dan C.
(2) Nope, sounds like you need a refactor. I'd look to group some of those properties onto child classes - Andrew Bullock
(2) No I don't. Those cases are rare, but believe me it happens. Think (just an example) of a Person class with tens of unrelated fields. Real-world requirements are surprisingly complex sometimes. - Dan C.
(1) Then you've made my point for me, rare cases call for rare solutions ;) - Andrew Bullock
(48) Right. And the more often cases where you have medium objects? In the end, it's a choice you make and live with it. But arguments such as "it's ugly" or "it's used to hide bad code" are just childish. Some people are used to this and it helps code navigation... - Dan C.
(1) Some are are not (and hate the extra double-click it takes to expand a region they're interested in). In the end, it doesn't really matter, as long as it's the same for the whole project. - Dan C.
(6) Clicking ? Child classes ? You don't need to click. You can have hotkey. There is nothing worst then classes that are there just because you need to wrap something up that generally shouldn't be in class or function by its semantics. - majkinetor
(2) Anyway, every person has the environment in which it is most productive. If regions are part of it how can that be wrong? If not, how can that be wrong ? No reason really. Talking oposite is just imposing rules of your own universe into others, instead of understanding our differences. - majkinetor
@Dan I didnt say that, i said it hindered navigation and readability but yes its a choice, just not one i make :) @majkinetor, wrapping related properties into immutable child objects is a very common pattern of DDD, consider a Person with Address fields, why not stick them onto an Address struct? - Andrew Bullock
I can't see how #region and #endregion hinders readability, when you turn off collapsing. It's no different from // Fields... // End fields. As I said having them littering the class for every minor difference like helpers,private and so on is overkill - Chris S
(5) @Andrew: you didn't, however you took an awfully aggressive stance. As said by others, hindering navigation and readability is just a personal opinion. - Dan C.
(1) @Dan lol sorry, didn't mean to offend - Andrew Bullock
I would use partial classes once a class gets too big to read (and can't be refacored in more classes anymore). Personally I am more comfortable with having coherent stuff in a single file instead of "between lines 411 and 875". Shouldn't be overused though. - Marcel Jackwerth
The point made in the edit is the crucial one. - Daniel Earwicker
(8) Do you think regions should be added to this long list of comments. LOL - PeteT
(5) Do you really want to scroll through 30 private members + 30 properties for them when you look through a class, instead of grouping them into a region which describes their function, so they take up only one line instead of about 300? Structuring every class with regions unnecessarily can be annoying though. - Sandor Davidhazi
Is this correct just because he agrees with the OP? - DevinB
(68) Poor answer without any reasoning behind it. - Michael Barth
(40) -1 Aside from the fact that I do not agree (I prefer classes that use regions to group their members - no problem to just open all regions if you need to). This is a sarcastic opinion, not an answer. - galaktor
(3) Please choose the answer that reasons as the 'correct answer'. This answer is funny, but that doesn't make it "morer correcter". - bobobobo
(4) -1 In fact, i have two classes which require an obscene number of (not related other than it's a property of the class) properties, and i know for a fact that regions could be helpful there (i have to remember to actually use them). - RCIX
(2) -1. Regions are quite useful when used appropriately and do not detract from readability or manageability of code. While I use them to group fields, properties, constructors, and methods, I could understand someone seeing that as overkill; however one area I believe them to be particularly useful is in interface implementation. If my class implements many interfaces, I would much rather have #region IClonable<T> Members... #region ISaveable Members... #region IEnumerable<T> Members... #region IList<T> Members... and so on, than just an endless listing of methods. - Sahuagin
(1) haha you say no to region, cause it means your code is bad organized, but still you accept designer generated code? decide, to my minde the second of these is much more evil :) You wont find much of that in jave for ex. - mikus
2
[+49] [2009-04-16 10:23:21] Cerebrus

I use regions extensively and instantly dislike any code that doesn't structure its various members into logically separated "regions".

Usually, My classes are divided into the following regions:

  • Private Fields
  • Public Methods(including Public Constructors)
  • Private Methods
  • Public Properties

This is however, a generalization. Some people like to structure class members based on function.


I'm curious about these regions actually help you. When looking at a method do you assume things about it by virtue of being located inside a particular region? - Ed Guiness
Do you have different regions for all access modifiers or just public and private? - Ed Guiness
@edg: No,I don't usually need separate regions for each kind of access modifier. In such as case, I could use something like "Private/Protected Methods" which contain all the Private/Protected functions. I'd still keep the Public interface in a separate region. - Cerebrus
Please note that the answer provides an illustration and a general example. The regions have always helped me to quickly identify where a particular code smell might be located, when I do not know the name of a function. - Cerebrus
(33) I use regions, but I hate separating functions by accessibility in regions. I don't think they help. I think logical separation by functionality is a better way to organize code. - LeakyCode
(49) If there was ever a use for regions, this is absolutely not it. What does this achieve? All it does is obfuscate the code. You should organise your code by purpose and function, not protection level. What does that have to do with anything. This really grinds my gears! - Andrew Bullock
(3) Fields, Properties, Ctors, Methods (then methods regioned by their responsibilities) is my preference - Chris S
(30) How about a region for each letter of the alphabet? ;-) - Ed Guiness
I tend to follow these runs, but will add different region based on fxnality. Really, I use them to hide pieces that are not relevant to my current refactoring task. - Nathan
Thanks for all the support, guys! And for the downvotes and the sarcasm. Reached my daily 200 limit halfway through. If only I had known this 'answer' would get such a response !! :-) - Cerebrus
(4) For me, grouping by accessibility (well, it's actually by type, i.e. separate into Fields, Properties, Methods and Implementation) is kinda helpful. I find it that most of the time, fields and properties are "fire and forget", most of the maintenance work is in methods. Collapsible regions help here - Dan C.
(1) @Cerebrus: +1 for the inspiring speech. Go regions, go! ;-) - Adrian Grigore
Horrible idea - get the IDE to display members grouped for you. It's a total waste of your precious time to be doing it manually in the source code of every class. - Daniel Earwicker
@Earwicker: Unfortunately the IDE doesn't do that for us. With some configuration effort (namely, defining/customizing the Visual Studio's code templates, there are plenty of tutorials available), you at least get the regions by default when creating a new file. If I were to do it manually, I'd probably find it a bit painful too... - Dan C.
Protection level make sense sometimes you just need to know what is private/protected, public is pretty obvious with the ide but its nice if you just looking around in the class you know what you have access to a lot faster then going to each method and determine if you can extend it or not. - MrB
I see only one legit reason to use a region and that is to hide your comment. - Timmerz
+1 for the first phrase: I use regions extensively; -1 for everything that followed. From a #region fan. - nawfal
This is somewhat contrary to the newspaper metaphor stated by Uncle Bob in Clean Code. - SpaceTrucker
3
[+44] [2009-04-16 10:16:23] Ed Guiness

I use #regions to hide designer-generated code, but that's it.


(4) The only valid use for regions, but I avoid designer generated code in the first place - Andrew Bullock
(24) .NET has support for partial classes now, so designer generated code can be in a different file from user generated code. There is no good reason to use regions. - Wedge
Or maybe a good reason is bad code? - Eugenio Miró
4
[+39] [2009-04-16 10:28:48] Lasse V. Karlsen

Personally I don't like hammers, because you can break so much with them, including fingers.


if( #region == hammer ) // yea! else if( Noooooo! == hammer ) // booo! - Simeon Pilgrim
(1) What do you use for driving a nail into the wall, then? Using bare hands tends to be quite messy. Also, with the same reasoning you might justify using assembler over object oriented languages. - Adrian Grigore
(9) @Adrian: Swing and a miss. Not used to irony, eh? - Beska
(5) I'm really not sure this is irony. There are actually lots of people refusing to use good tools because they are afraid of misusing them. Take Linus Thorvalds, for instance, who claims that C is superior to C++ because C++ "leads to bad design choices". Quite the same attitude as lassevk's answer. - Adrian Grigore
(3) +1 Adrian, just cause someone doesn't know how to use a tool, doesn't make it a crappy tool. - SnOrfus
(2) And of course I don't actually not use a hammer, it's just that a discussion about whether a tool is aproriate for everybody is just plain stupid, it isn't useful, so I thought I'd chip in my 2 cents about hammers, which is just as pointless. Should I dictate whether you should use a hammer or not just because I don't like it? (which I do, just to clear that up) - Lasse V. Karlsen
(2) Regardless if I agree to this statement in the current context, it is a great statement. I've so many discussions about "bad" language features because they are misused. In my opinion inheritance is often misused, so it is evil. To be consistent it shouldn't be used anymore. - Stefan Steinegger
5
[+34] [2009-04-16 10:32:46] Ian

I actually like using regions, and feel they can be very useful for making logical groupings in a class. For example I had a class with various derivatives which certain methods corresponded to different things (visual, functional, child object management). Splitting these up into regions makes it clearer where things are, and can give you a good overview if you have appropriately named regions.

You could split these into partial classes, like the designer class is. But ultimately that reaches a very similar conclusion, and you have a lot more class files that you'll need to name appropriately.

You can also use searching, but some of the projects I'm working on, searching is slow. And it's much better if you can learn your way around the code, and find things quickly than having to wait for a time consuming search.

I have also used them within a few algorithms for understanding and maintainability. Honestly I don't think I'd advocate this and it's always better to split things up into methods, but that isn't so easy with the algorithms that I'm working with. Therefore breaking it up into logical sections, and then adding more comments + detail within the regions seemed the best bet to me at the time, and honestly is taking a modular approach to it. You have a method, with a description of what it does. You have regions within the method that explain what that section of code does (with comments) and then you can go down to individual lines of code which may also be commented. So it helps you to drill down to get more information quickly and easily.

I think they're are fine for logical grouping in classes. I think they can work in code/methods but should be avoided if splitting code into more methods is the most suitable approach.


(5) +1 because there was no reason to down vote a well explained answer on a subjective question. - sipwiz
(2) +1 Good argument. But how about just splitting your drawing code from your data code? Uber classes that know about persistence, visualization, security, etc. are maintenance nightmares. These orthogonal functionalities should be split into a centralized cross-cutting concern. In this case, #regions are just hiding this mess. - Frank Krueger
6
[+29] [2009-04-16 10:37:14] user88637

Does it really matter? I am seriously asking this question.

A normal IDE probably has a feature to completely turn off Region hiding. So If someone doesn't like it he can just turn it off. So he will never have something hidden. And if someone like it, then he just use it.

I believe that it is very subjective. A good programmer knows what pieces of code he has to look at no matter if something is hidden with region or not.


I would agree with you if it wasn't a precident. This is the broken windows concept in psychology. That the house is sacred until you allow flaws to stay around, which sets the precident of. "Well its like this over there", and junior people use regions to hide code. To Hide bad code. - DevelopingChris
(1) Even if I turn off the comments, they are still writing bad code because they can hide the pain they are causing my eyes. - DevelopingChris
(2) The problem is that different people want different things hidden. The options are not just regions and no regions. For example, I only use regions to hide designer-generated code, and the odd inline sql script. I don't want those #privates, #protecteds, #publics regions. An IDE pref cannot help me. - Blorgbeard
7
[+19] [2009-04-16 10:31:46] Adrian Grigore

I disagree with the article's author. Using regions does not automatically make you write bad, unstructured code. It really depends of what you are using them for.

For example, I use them to mark different parts of my MVC controller classes, such as Create, Edit and Delete. Edit and Delete contain two different methods (POST and GET) plus a custom View Model in some cases. By wrapping each of these functionalities in one outlining region, I can work on one of them for a longer time without having to see all the other functionalities that do not concern me at the moment anyway.

This does not influence my style of coding. It just makes the file a bit less cluttered with details I do not need to see at the moment. Therefore this usage of code regions is not bad.

If I used code regions to hide a myriad of helper functions and objects which might be better off in their own separate objects, that would be a completely different story. But as I said, I really depends on what you are using code regions for.


in the mvc case, you shouldn't have multiple methods, and collapse to definition would 100% solve the only look at action x, if you have that big of controllers, then theres a smell there. - DevelopingChris
+1 for grouping by functionality, as opposed to grouping by type - TJB
@ChanChan: Actually in MVC you usually have one POST and one GET method per functionality. Pair that with a custom-shaped ViewModel which might be different for each functionality (page 107 in Scott Hanselmann's NerdDinner PDF chapter) and you have one block of functionality. No bad smell here. - Adrian Grigore
Wholly agree with that interpretation. +1 - Cerebrus
8
[+19] [2009-04-16 22:43:04] Wedge

To turn off region collapsing in Visual Studio:

CTRL + M, CTRL + P

Or, from the menu:

Edit > Outlining > Stop Outlining


That's why I said 'easily accessible'. It's a little unwieldy, there isn't a single toggle option and turning it back on has no keyboard short-cut in the C#2005 scheme, and I would to see the region markers disappear when turned off or at least made less intrusive. Admittedly you can get around these issues easily, assigning keys/buttons etc, but I think it could be better: I'd also like to be able toggle by region types (e.g. comments) & define my own types, with different colours symbols etc. - Gordon Mackie JoanMiro
This should be the top answer! - RichardOD
(7) +1 for indirectly teaching me the SO <kbd> tag... - advs89
(1) I enjoy code folding. I do not enjoy "region" code folding. Ctrl+M,P unfolds and Ctrl+M,O folds (but unfortunately collapses regions and not just methods/properties/comments). I think it would be far more beneficial to have a "remove region" oppose to just removing code folding completely. - user295190
Except of the fact that you still need to manage them because they don't disappear from the code! - Stefan Steinegger
9
[+10] [2010-02-05 19:41:19] alchemical
  • Regions hide code -- I want to see the code.

  • Regions provide text info about the code -- comments do that nicely.

  • Even turning off the regions leaves a bunch of #region code, cluttering up the code, they are colored blue which makes them look like code rather than comments.


10
[+8] [2009-04-16 10:27:51] Guffa

I use regions to group the members of classes, like Properties, Constructors and Methods. It helps keeping a nice structure in the classes, and when compacted you get a nice overview that you can easily navigate without having to use the search (which sometimes takes several seconds just to show up...).


(4) if your classes have 1 responsibility, you usually have to edit multiple types of members on the class, which makes the regions annoying, since the property for this private is not near it. And methods that use it are over there in a bucket. - DevelopingChris
If you want to group class elements, you do not need to use regions as Class View in studio does the trick. - isntn
(1) @ChanChan: During maintenance, you make changes to methods (only) much more often than to an entire class. - Dan C.
(1) Even if editing several members, I find them easier in their bucket than arranged in some more or less arbitrary fashion. The Class View can help me find members, but it does nothing for code structure. - Guffa
(1) Bad idea. As bad as writing comments that needlessly duplicate information that is obviously present in the code. Providing a grouped view is the IDE's job. - Daniel Earwicker
Annoying is akey word for me when it comes to regions. Except maybe for generated code, when I open a class I went to the effort to do so to see the code in it. With regions it's like opening the fridge only to find that you can't get anything without opening yet more doors. Yes, I want to see the properties, constructors, variable declarations etc. Ctrl-M/O/ is disruptive -- vertical scrolling is easy. - Tim Tonnesen
@Tim Tonnesen: Scrolling scrolling scrolling scrolling scrolling scrolling, while constantly reading to try to find what you are looking for... I rather just click once and find exactly what I was looking for. Going with your kitchen appliance comparison, imagine opening the freezer, and there are no shelves or drawers, everything just falls out over you when you open the door... - Guffa
11
[+8] [2009-04-16 12:56:32] Pat

I say yes... Coupled with Regionerate [1] and my own flavor of regions I love it. I use this on most classes unless they contain such little code that it is unnecessary.


Regions I declare are as follows:

Declarations
Constructors
Overrides
Methods
Properties
Event Handlers

[1] http://www.rauchy.net/regionerate/

I would identify with this sort of grouping. +1 - Cerebrus
Thx for the tool m8 :) - majkinetor
(1) +1: Especially when using an MVC pattern, UI event handlers that just call methods on the view can be tossed in a region. - SnOrfus
Grouping like that is the IDE's job, not for the coder to have to maintain manually. I find it incredible that anyone would adopt this behaviour without stopping to question it! - Daniel Earwicker
(1) @Earwicker A tool is maintaining it, there is no manual action necessary really. I think the real question is how a team adopts it; not if a single person does. Currently I've had no complaints. - Pat
I don't even go that far. For the most part I just have Fields, Properties and Methods. - Nick Bedford
12
[+7] [2009-04-16 17:48:02] dkpatt

I use them to hide huge sets of properties that tend to be in the way while looking through code. I know... OCD... but it drives me nuts otherwise.


(3) Excellent example of why regions exist. - pearcewg
13
[+5] [2009-04-16 10:15:32] Hank Gay

I say "No!" to regions, code folding, and anything else that resembles them. When I'm looking at a source file, I want to see the source. I use search to move around inside the file, so regions can only slow me down.


(10) In VS, search will (by default, you can change this) include hidden code. This includes incremental search. - Richard
(4) That doesn't speed up my work, though. If I don't want to see some code, I scroll it away. If there's so much code in the file that this isn't practical, it's usually a good sign that there are larger problems. - Hank Gay
(1) +1 hank, if its so bad that you can't just read it, its bad, fix it. - DevelopingChris
(1) @Hank: "it's usually a good sign that there are larger problems." Say that again when you inherit a project whose source files are K's of lines. "I could toss some things in regions and get to work, or spend 2 weeks refactoring and get fired." - SnOrfus
(4) I have a project where the classes run into thousands of lines. Not once has code folding or regions or anything else fixed a bug. - Hank Gay
else -> similar - Hank Gay
(4) I have a project where the classes run into thousands of lines. Not once has not using code folding or regions or anything similar fixed a bug. I don't get your point. Are regions supposed to fix bugs? - nicodemus13
14
[+5] [2009-08-05 20:26:35] Kyralessa

Regions are useful for hiding code that does not need to be edited.

For instance:

  • Designer-generated code
  • Code emitted by any other code-generation tool
  • Code that's commented out but kept for future reference (due to fear of losing it in the source-control system).

Regions shouldn't be used for code that does need to be maintained, because they make it too hard to see the code.

In particular, they don't work properly with outlining. CollapseToDefinitions also collapses the regions. There's no command to collapse method/property bodies but expand regions.

For those of you unfortunate enough to work in a shop that's enamored of regions, here's a macro you can use to collapse methods and properties but expand regions:

Sub CollapseToDefinitionsButExpandAllRegions()
    DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
    DTE.SuppressUI = True
    Dim objSelection As TextSelection = 
        CType(DTE.ActiveDocument.Selection, TextSelection)
    objSelection.StartOfDocument()
    Do While objSelection.FindText(
        "#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
    Loop
    objSelection.StartOfDocument()
    DTE.SuppressUI = False
End Sub

You can assign that to a key so you can easily collapse but still see the code. The only drawback is that it also expands regions that are inside a method body, which means those methods won't be collapsed. If anyone has any improvements that'll solve that problem, feel free to add them.


15
[+5] [2010-01-04 10:59:11] SoMoS

I use them always but never to hide ugly code. In fact most of the time I use them expanded. Is just a way of enforce code elements organization. I normally have those regions:

Attributes
Constants
Properties
Events
Public Methods
Event Handlers
Private Methods

There are moments while programming that some parts of what you code are "noise" because they are not related whit what you are doing at this moment (for example, attributes when you are defining the public interface, normally properties can be hidden when they have been coded if they are simple getters / setters, etc).

Having less code visible at the screen lets you concentrate in what matters (the code you need).

As TJB said, there are valid uses of Regions.


16
[+4] [2009-04-16 10:29:53] TcKs

I use regions in several cases.

  • explicit implementation of
  • interface(s) nested types
  • synchronous and asynchronous methods

17
[+4] [2009-04-16 11:24:08] Nils

I code c# with WPF and found #region quite useful, for example to hide all the dependency property registration and the wrapper CLR properties. Another usage of the #region construct is for example to hide the geometry of an object which extends Shape; once the geometry drawing algorithms is coded, I want to focus on other things and therefore hide it in #region internal geometry.


the answer is no :D it helps to structure code - Nils
+1 I also like to wrap each dependency property and its associated stuff into its own region. I also use ReSharper and if I use automatic code clean up and have it re-order type members, it will keep the stuff in those regions together rather than scattering the pieces around. - jomtois
18
[+3] [2009-04-16 10:18:36] Richard

Regions and code folding can be useful where there are multiple distinct parts to a class, e.g. in a WinForms form separating layout from calling into business logic.

But they are not a substitute for good coding.


(5) Surely your business logic should live in its own class, rather than inside your WinForms form...? - Richard Everett
(3) I think that is an encapsulation mistake, and regions are the smell that help you find that garbage. - DevelopingChris
@Richard E: Yes, will correct, methods/event handlers linking the form to underlying business logic. - Richard
19
[+3] [2009-04-16 11:04:10] sipwiz

I use regions and like them. Amongst other things I find them very handy to wrap up logical groupings of methods in a class. For example I'll have a region for "UI Methods" another region for "Server communications" etc. It makes it very easy to narrow the focus when reviewing a class.

As far as using regions to hide bad code I don't see how anyone could pretend to do that; right click, select Toggle Outlining and all the regions are expanded, not really somewhere safe to hide. If I wanted to hide bad code I'd write a C library and access it with from a .Net assembly with PInvoke, that would keep 95% of .Net developers out.


+1 for being so funny (C library + PInvoke!) LMAO! - Cerebrus
20
[+3] [2010-05-26 22:10:24] Rachel

I guess I'm in the minority with my preference on this, but I personally love regions, and have a snippet that I use to add the same structure to every class I write, except the most trivial classes that contain only a few lines of code that fit on one screen. When I try and read someone else's classes that don't use that same consistent approach to filing away the elements that make up the whole object, I find it doesn't make as much sense to me initially, and makes it more difficult, but by no means impossible, for me to grok what my fellow developer was trying to do.

Despite my personal preference, which I recognise is only a personal preference, I don't understand why a tiny minority of people get so hung up over their use by others. I've even encountered such excitable opinions as "they make code un-maintainable" and "they represent bad design"*. [*Both of which comments my last boss put on his public-facing blog, then denied they alluded to my use of regions when I challenged him about his comments (which he hadn't expressed to me personally, and seemed surprised and embarrassed I had read). When I showed him how trivially easy it is to toggle between Collapse/Expand all regions using the Ctrl-M, Ctrl-L and Ctrl-M, Ctrl-O shortcuts in Visual Studio, thereby seeing my classes in the way he preferred, he looked more sheepish still. His lack of courage in criticising my style publicly in a way he thought I wouldn't discover behind my back, and his inability to defend those publicly-expressed criticisms of my coding style when challenged on his views, is a large part of the reason why he is now my ex boss, and left to do it all by himself :) ].


21
[+2] [2009-04-16 10:24:22] Nick Allen

I use regions to hide away large sets of properties and member variables, that's it though


22
[+2] [2009-04-16 12:42:34] majkinetor

I wonder, how can anybody say that regions are bad ??? I mean, its like saying comments are bad, because regions are just commented containers. Why even arguing about it... don't' use it if you don't like it, don't theory craft about the thing cuz you don't like it.

I see that lot of people here seem to talk about only one category of programs - those that involve large teams, developed for years, with requirements and people changing constantly, in which case you should probably stick with the best practices and patterns. But that's only buisnis programming. There are different kind of people and different kind of programs and not all of them have to look the same !

Now, back to the regions. I use them exclusively. If I have to do 3 tasks in 1 function, I create 3 regions. Refactor? Yeah right... :S How many times will you repeat that. You refactor, I am perfectly happy with my regioned code the way it is.

In order to be good user of regions, you must IMO, implement procedure similar to this one:

  1. Hotkey to toggle region, and to collapse entire code. I keep ctrl + darrow as hotkey for that as while u surfe the code you can quicly jump in out of region.
  2. HotKey to collapse all regions, so I can quickly create what I call TOC for the code file. I even use .cs file to store common project information (docs, notes etc..) which doesn't contain C# code at all, it just has .cs extension so I can organise it using regions.
  3. Macro to create region of selected code. I keep it on F12

    #Region "CreateRegion" :P    
    Sub CreateRegion()
        Dim regionName As String
        Dim sb As New StringBuilder
        Dim regionBegin, regionEnd As String
        Dim selection As TextSelection
    
    
    
    regionName = InputBox("Enter region name:", "REQUEST FOR INFO")
    
    
    'We don't want to go any further if the user clicked cancelled
    If regionName.Length = 0 AndAlso WasInputBoxCancelled(regionName) Then Return
    
    
    selection = DTE.ActiveDocument.Selection
    
    
    Select Case GetActiveFileExtension()
        Case "vb"
            regionBegin = String.Format("#Region ""{0}""", regionName)
            regionEnd = String.Format("#End Region '{0}", regionName)
        Case Else
            regionBegin = String.Format("#region {0}", regionName)
            regionEnd = String.Format("#endregion {0}", regionName)
    End Select
    
    
    sb.Append(regionBegin)
    sb.Append(vbNewLine, 2)
    sb.Append(selection.Text)
    sb.Append(vbNewLine)
    sb.Append(regionEnd)
    sb.Append(vbNewLine)
    
    
    selection.Delete()
    selection.Insert(sb.ToString(), vsInsertFlags.vsInsertFlagsContainNewText)
    selection.SmartFormat()    
    
    End Sub #End Region 'CreateRegion

I wish there are regions in all editors :D


(3) Oh my sweet Jebus! You would really use regions within a method? Please tell me your extracting the urine? Please? - Binary Worrier
(2) @Binary - I've seen a "#region structs", enclosing a single struct that had a #region enclosing its members! help us all. - gbjbaanb
@Binary: I can tell you many things about my urine. If you want to improve your health with some great nutriceuticals I can send you some to see if there is any improvement. @gbjbaanb: Where did you see that ? In Learn VBA-4-7-minutes course ? - majkinetor
@majkinetor: Please forgive the flippantancy of my previous comment. Folling the Single Responsibility Principal leads us to write short methods. The idea of a method long enough to warrent regions makes my mind boggle. Personally I dislike regions because they hide code, when I'm writing code the last thing I want to do is hide code. It may be my failing, but I can't imagine a scenario where I would ever put a region into a method. - Binary Worrier
(1) Sure. Personally, I think SRP is important goal. However, that doesn't mean that it necessarily leads to short methods. It is a principle, a system of beliefs, not a mathematical theorem. It might be the best thing to be done generally, but that says nothing about any concrete problem. The best thing the one can do is acknowledge differences and learn practices that can transpose things you encounter to suit your habits. In this case, its trivial: turn regions off (better, hotkey it). That will not fix badly designed code tho, and if regions are there 4 that reason, better to let them stay. - majkinetor
In any instance, optional organisational features are better thing to have then limited organisation options. Regions are organisational thing. Reports typically have many different ways to present the data. Region is one of those ways that say something about authors intent and line of thought. It can't be bad if it is optional thing for both parties. - majkinetor
23
[+2] [2009-04-16 13:08:49] Gordon Mackie JoanMiro

I both like AND dislike regions.

They are great for organising code into general areas such as 'all properties', 'all fields' etc and then hiding them away - great for stuff like control development were there are usually a lot of properties with backing-store and auto-props can't be used if you're following a notify property change pattern.

And they are great when you are implementing several interfaces and you want to group the interface implementations separately from the main implementation.

But they do get in the way when you want to see the entirety of the code or you are browsing through it looking for something. And even worse when it's someone else's code and they don't agree with your conventions for naming and grouping :-)

What I would like to see is an easily accessible feature in Visual Studio that allowed a 'with-regions' and 'without-regions' toggling option so I could have the best of both worlds when it suited me. Perhaps such things will be easy to implement as extensions to the IDE in VS2010.


24
[+2] [2009-04-16 14:56:32] Aaron Daniels

Personally, I hate regions, and just say NO!

But if I'm working with other developers that use them, I will quell my opinion, as it is just that, an opinion. Being consistent across a codebase is better than forcing my will upon others.

Most of the regions I see separate out different sections, (public methods, public parameters, etc..). I prefer using StyleCop, as this enforces the proper segregation of putting all of your public methods together. I see a region marked as "public methods" as a potential lie, because there's nothing to tell you if public methods exist outside of the region.

On this note, the one thing that I have recently used a region for was to exclude code from StyleCop. Any region with the text "generated code" will be excluded from its criticism. Of course, this should only be used in an extreme circumstance.


25
[+2] [2009-04-17 12:34:06] User

We have regions all around in the software. I absolutely hate them. It's so much noise in the code.

Since it is a German company I suppose they should generally like regions as that nation loves to organize everything even when unasked.


26
[+2] [2009-04-30 14:16:21] MatthewMartin

Given the code base I'm using now, it appears most developers believe a region is a class. Regions often indicate code that is unrelated to the rest of the code in the file, share few dependencies, etc, in otherwords signs that it should be a separate encapsulated class.

Regions encourage bad programming on the level of sabotage.

Regions are the rug under which sloppy developers sweep their shame.

As a maintenance developer, I can't read code with Visual Studio constantly collapsing and hiding code from me.

I remove all regions on sight.


27
[+1] [2009-04-16 11:10:07] RYFN

it's strange, a guy I work with who I would consider our most talented programmer uses regions all over the place. but then he also writes comments like

//create thing
thing someobject = new thing();

With me being the junior and he being the senior engineer, these are things I try to avoid picking up. But like others have mentioned, sometimes it's easy to assume that's the way it's done if you're learning and you see it there already!


(1) This is the perfect analogy, I think. Redundant information in regions is just as bad as redundant information in comments. In exactly the same way, it goes stale as the code is maintained. - Daniel Earwicker
28
[+1] [2009-04-16 11:52:18] agnieszka

I simply use it for grouping:

  • grouping methods by what they do, for example if there is a method AdjustDisplay and it uses Resize, MoveImage etc., i would put them in "adjusting display" region;
  • i don't know if it's a good idea but i sometimes group by private/public, so that i can easily find methods used from outside or helper methods - private ones.

29
[+1] [2009-04-16 13:22:42] rob

The use of regions tends to border on a religious debate, but I tend are with the use of them although I do wish they were more of a comment directive (e.g. /// #region to start a block) as opposed to a preprocessor directive.

In terms of my use of them:

  • Minimization of long strings - In short, if I have some really long string hard coded in the source code (typically a query that isn't being made into a view) then I will use a region around it so I can get it out of the way of other more relevant code.
  • Minimization of long blocks of private members - Fairly self explanatory; although automatic creation via properties in C# 3.5 is minimizing the need for this.
  • Minimization of long blocks of class properties - This one should be self explanatory and it more to help me scroll through a file quickly than anything else. Granted I could just search for what I am looking for, but when looking at a file I sometimes want to read through the entire file but looking at a bunch of property declarations doesn't add any value and wastes my time.
  • Minimization of blocks of constant declarations - This last one should also be be fairly self explanatory.
  • Minimization and grouping of required reimplementation details - Similar to what was mentioned by dance2die [1], if I need to implement some code for use of another class I might throw a region around it as it should never really need to be changed or be that unique.

Out side of those areas, I try to avoid regions for the most part and if I see a region inline with some code then it usually raises a red flag in my mind.

[1] http://stackoverflow.com/questions/755465/do-you-say-no-to-c-regions/756017#756017

30
[+1] [2009-04-16 18:05:20] Don Reba

The author assumes everyone writes in Visual Studio with ReSharper. Actually, regions are very useful for folding in Vim.


31
[+1] [2009-04-17 20:28:22] Nazadus

I use them to keep Stylecop happy and to make it easier to find code.

I'm still trying to define a sane style for some things.. for example, should all public classes be in their own file? I dunno. I'm trying all sorts of things to find out what looks the cleanest.

I should also note that I like to group certain things together at times. For example, I may have in my Methods region sections for overrides, utilities, etc. For event handlers I'll try to group like things together such as menu items or things that there may be a lot of similar code you may want to get out of your way. Otherwise, everything is assume alphabetical -- as often as people.

Here is the code snippet I apply to all forms:

#region Constant Fields
#endregion Constant Fields

#region Fields
#endregion Fields

#region Constructors
#endregion Constructors

#region Deconstructors
#endregion Deconstructors

#region Delegates
#endregion Delegates

#region Events
#endregion Events

#region Interfaces
#endregion Interfaces

#region Properties
#endregion Properties

#region Indexers
#endregion Indexers

#region Methods
/*
 * Order: (Static comes first, then instance in each section (e.g. public static, public instance, private static, private instance)
 *  public, internal, protected-internal, protected, private
 */
#endregion Methods

#region Structs
#endregion Structs

#region Classes
#endregion Classes

32
[+1] [2009-04-30 10:02:44] Binoj Antony

Regions are actually a form of encapsulation for the programmer, but only at design/coding time, it has no effect at runtime, although it would have been nice to have that.....;)


33
[+1] [2010-03-25 08:55:20] Benjol

I've just disabled regions for a simple reason, they screw up RockScroll [1], and that's the one VS add-on I can't live without!

[1] http://www.hanselman.com/blog/IntroducingRockScroll.aspx

34
[+1] [2010-05-26 22:47:59] Nick Bedford

Regions help separate large groups of code items (such as functions, fields/properties etc).

If you think they're used to hide "bad code" then you're probably writing bad code yourself.

They're very useful for finding items in large classes.


35
[0] [2009-04-16 10:18:33] Lucero

We use a quite strict layout of the class code files (basically nested types such as classes, enums, delegate definitions etc), then static members with fields first, then instance members with fields, then constructors, then the rest). Some tools such as ReSharper support automatic reordering of the members, so that maintaining this structure is not painful at all. But it makes navigation in the file quite intuitive and since then, I haven't used regions anymore.


36
[0] [2009-04-16 11:39:59] isntn
  • Use regions where they are automatically generated. Do not waste time deleting them ;-).
  • Expect generators to use regions.
  • Use Class View, Search, Incremental Search, Code Folding (and shortcut keys), Source Outliner powertoy, ReSharper, Code Rush etc effectively. Do NOT use regions for functions provided by IDE, tools and views.
  • Within single method, if algorithm is complicated, use (effectively) regions to document
  • Use split window to look at two locations in one source file.

I wrote a macro that deletes them, so the first point is no obstacle. Third point (get the IDE to do automatic outlining) is excellent, absolutely right. - Daniel Earwicker
If you can, pls share macro somewhere :-) - isntn
37
[0] [2009-04-16 13:00:58] Sung

I use #region only to hide Dispose logic (for IDisposable [1] implementation)

For all other cases, I try to refactor and keep my class small enough not to use regions.

[1] http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

38
[0] [2009-04-16 13:57:37] Crash893

I'm by no means a super programmer

but I use regions for 3 reasons

1) separate methods from form controls ( I know it sounds silly but it's a good way for me to not have to scroll through a ton of code to see what I need)

2) to clump code that doesn't appear to belong together but does ( calling a windows dll then the subs related to that

3) the IDE already uses it in various other parts so I figure it can't be that bad.


39
[0] [2009-04-17 01:29:21] pearcewg

I use regions for sections of code which I want to collapse, and I want to have other developers not touch.

I put a comment summary in the region line itself, and then a summary at the top of the code block that explains what the block it, why it shouldn't be touched, and why it shouldn't be refactored (why it belongs exactly where it belongs).

Additionally, I haven't printed out a source file in 15 years. It is a general good practice to use regions for organization (in addition to other methods).


40
[0] [2009-04-17 12:27:31] Michael Stum

I don't use regions, mainly because the #endregion Tag does not have the name. It's nice that you can put "#region name", but it should be mandatory to have "#endregion name" as well, otherwise a compiler error should be thrown (oh, and please none if this "You can just use a comment like #endregion // name", because we all know that this won't work out).

BTW, is there a key combination to jump from a #region to it's #endregion tag and back?


Look at my comment, I like it like that for the same reasons. But I use #endregion string I agree, it should be mandatory to have a name there. I've also seen people comment closes braces for name space and the primary class of the file. - Nazadus
Comments aren't required at the end of classes, methods, or blocks, either. Would you prefer that they were? - Jon of All Trades
41
[0] [2009-04-17 20:37:25] Dean

I love/hate regions.

I have a region for each of Constants, Enum's, Events and Variables. I feel that these are things that I don't touch too much, so they can be hidden without causing me any problems.

I never use it for code.


42
[0] [2009-05-08 13:55:26] janzi

I only use regions for putting a neat header before my properties / constructors / methods etc. Never to hide any actual code. It just irritates me. Better then to use ctrl-M+O to collapse to definitions.


43
[0] [2009-12-11 16:40:39] Vinz

My first response to a file containing regions is always CTRL + M + L to expand them all.

At some companies I've worked, they had those visual studio file templates that contained all the regions for the different protection levels and so on. This used to drive me nuts and I had some discussions about me not using them...

Glad to see that many people think like me on the subject. Thanks for sharing the fact that satan himself added the feature, I didn't know that but it does not surprise me!


44
[0] [2010-02-01 16:37:24] Nick Gotch

The best reason IMHO for using regions is for organizational grouping.

For example, I have a SearchDialog where a user can enter field patterns and out pops a search expression used by the parent window. In this code (which gets fairly long) I have a region for "Save/Load Functionality" and another for "Search Expression Generation." With all the members in this class, I've found it especially useful to have all the code related to a specific element of functionality grouped into a single place.

This level of functionality isn't large enough to warrant its own class but yet having it in a single location does make going back in and working with it MUCH easier.

Another helpful use for regions is in interface implementations, particularly when a class inherits from a multitude of interfaces.


45
[0] [2010-02-02 17:51:07] Alvaro

I've written a tiny Region Killer tool that handily removes all #region and #endregion from your source code, therefore easing the pain caused by their unholy appearance.

Get it at http://code.google.com/p/rkill/

Have a nice day and remember to eat cookies with milk every afternoon.


46
[0] [2010-05-26 22:22:54] jgemedina

depends how they're used, i just use them to organize large code files, and desginer generated code


47
[0] [2010-12-07 09:04:54] GaryMcAllister

I think Anything that needs to go into a region is doing too much and can generally be abstracted away into another type / class to make the code more readible and easier to maintain.


48
[0] [2011-03-09 09:49:08] RB.

One gotcha to be aware of is that, by default, Studio "Find in current document" will not search through closed regions. There is an option to "Search in Hidden Text", but that is off by default.

Find in Solution, or Find in Project will always search in closed regions however.


49