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

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?

+2  A: 

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.

Hank Gay
In VS, search will (by default, you can change this) include hidden code. This includes incremental search.
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 hank, if its so bad that you can't just read it, its bad, fix it.
@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."
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
+105  A: 

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 anyone?

Andrew Bullock
The dreaded feature request nr 666 ;-).
#region Cocytus ;)
I assume you disable code outlining then? This allows you to ignore them.
No, my development team just writes sensible, clear, well factored code in the first place.
Andrew Bullock
Is 500 lines too much?
Chris S
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 http://en.wikipedia.org/wiki/Single_responsibility_principle
Andrew Bullock
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
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.
Nope, sounds like you need a refactor. I'd look to group some of those properties onto child classes
Andrew Bullock
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.
Then you've made my point for me, rare cases call for rare solutions ;)
Andrew Bullock
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.
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.
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.
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.
@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
@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.
@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 J.
The point made in the edit is the crucial one.
Daniel Earwicker
Do you think regions should be added to this long list of comments. LOL
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?
Poor answer without any reasoning behind it.
Michael Barth
-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.
Please choose the answer that reasons as the 'correct answer'. This answer is funny, but that doesn't make it "morer correcter".
-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).
+27  A: 

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

Ed Guiness
The only valid use for regions, but I avoid designer generated code in the first place
Andrew Bullock
.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.
Or maybe a good reason is bad code?
Eugenio Miró

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.

+2  A: 

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.

Surely your business logic should live in its own class, rather than inside your WinForms form...?
Richard Ev
I think that is an encapsulation mistake, and regions are the smell that help you find that garbage.
@Richard E: Yes, will correct, methods/event handlers linking the form to underlying business logic.
+45  A: 

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.
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.
check http://stackoverflow.com/questions/750915/how-do-you-arrange-source-code-elements-in-c-3-0
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.
Mehrdad Afshari
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
Fields, Properties, Ctors, Methods (then methods regioned by their responsibilities) is my preference
Chris S
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.
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 !! :-)
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.
@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.
+2  A: 

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

Nick Allen - Tungle139
+7  A: 

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...).

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.
If you want to group class elements, you do not need to use regions as Class View in studio does the trick.
@ChanChan: During maintenance, you make changes to methods (only) much more often than to an entire class.
Dan C.
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.
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
+10  A: 

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

Lasse V. Karlsen
if( #region == hammer ) // yea!else if( Noooooo! == hammer ) // booo!
Simeon Pilgrim
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
@Adrian: Swing and a miss. Not used to irony, eh?
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
+1 Adrian, just cause someone doesn't know how to use a tool, doesn't make it a crappy tool.
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
+3  A: 

I use regions in several cases.

  • explicit implementation of
  • interface(s) nested types
  • synchronous and asynchronous methods
+11  A: 

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.

Adrian Grigore
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.
+1 for grouping by functionality, as opposed to grouping by type
@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
+22  A: 

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.

+1 because there was no reason to down vote a well explained answer on a subjective question.
+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
+16  A: 

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.
Even if I turn off the comments, they are still writing bad code because they can hide the pain they are causing my eyes.
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.
+3  A: 

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!
+1  A: 

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!

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
+158  A: 

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!

+ 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")
+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.
IMHO this should have been the accepted answer
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.
THIS is what the accepted answer to this question should have been.
Thanks all for the nice comments, good to see people are being open minded.
Love your answer and agree with you.
@rob: let all the thinking people downvote ((that answer)) (http://stackoverflow.com/questions/755465/do-you-say-no-to-c-regions/755482#755482) to Hades! or something of that nature.
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
+1  A: 

The other day we had a discussion about this at work.

Conclusion: regions represent a code-smell. If your code needs them you should probably refactor.

One of the worst examples I encountered was a method, spanning about 7 screens, which used regions as a twisted form of comments:

#region GetDataForDatabase
.. do stuff..

#region FillTheCollection
.. do stuff...

So, that's an example of NOT using regions effectively. This post contains a few possible good uses for region. But I'm still not convinced...

Ruben Steins
I can't be the only person that wants to punch someone in the face everytime I read the words "code smell"
Matthew Whited
Wow. Why the agression when you read "code smell"? I think the term "code smell" pretty much sums it up. What would you propose as alternative to "code smell"?
Ruben Steins
You all seem to forget that real life is different then academic best approaches. On my job, the boss can enter the scene any moment and demand program for tomorrow. If case was so simple I wouldn't mind much, but it always happen that very big and complex systems are dead-lined way back its required time for the best design. Its even "scientifically proven" that most projects are not given enough time to be designed well. Regions are quick and effective way to explain something about your code when such thing happens (it rarely doesn't happen tbh, i.e. open source )
Writing good, well-factored code shouldn't take more effort or time than writing bad code does. Well-factored code doesn't require regions to be readable.
Ruben Steins
+4  A: 

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
+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.
  • 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 :-)

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.
+5  A: 

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(vbNewLine, 2)
    selection.Insert(sb.ToString(), vsInsertFlags.vsInsertFlagsContainNewText)
    End Sub #End Region 'CreateRegion

I wish there are regions in all editors :D

Oh my sweet Jebus! You would really use regions *within a method*? Please tell me your extracting the urine? Please?
Binary Worrier
@Binary - I've seen a "#region structs", enclosing a single struct that had a #region enclosing its members! help us all.
@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 [email protected]: Where did you see that ? In Learn VBA-4-7-minutes course ?
@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
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.
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.
+5  A: 

I say yes... Coupled with Regionerate 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:

Event Handlers

I would identify with this sort of grouping. +1
Thx for the tool m8 :)
+1: Especially when using an MVC pattern, UI event handlers that just call methods on the view can be tossed in a region.
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
@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.
I don't even go that far. For the most part I just have `Fields`, `Properties` and `Methods`.
Nick Bedford

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

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

Sung Meister
+2  A: 

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.

Gordon Mackie JoanMiro

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, 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.


I'm by no means a super programmer

but I use regions for 3 reasons

1) seperate methods from form controls ( i no it sounds silly but its a good way for me to no 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.

+1  A: 

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.

Aaron Daniels
+4  A: 

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.

Excellent example of why regions exist.
+1  A: 

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

Don Reba
+11  A: 

To turn off region collapsing in Visual Studio:


Or, from the menu:

Edit > Outlining > Stop Outlining

Gordon Mackie JoanMiro
This should be the top answer!
+1 for indirectly teaching me the SO <kbd> tag...

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).


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?

Michael Stum
Look at my comment, I like it like that for the same reasons. But I use #endregion stringI 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.
+1  A: 

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.

+2  A: 

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

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.


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.....;)

Binoj Antony
+2  A: 

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.


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.

+4  A: 

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.SuppressUI = True
    Dim objSelection As TextSelection = 
        CType(DTE.ActiveDocument.Selection, TextSelection)
    Do While objSelection.FindText(
        "#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
    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.


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!

+3  A: 

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:

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.


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.

Nick Gotch
+1  A: 

Hello guys, 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.

+2  A: 
  • 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.

+1  A: 

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

+2  A: 

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 :) ].


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


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.

Nick Bedford