Just say No! to C# Regions

February 29, 2008

I’ve seen lots of C# code over the last few days, and 100% of it contains the #region construct. So far, I have see it used in only one way: to hide big code blocks. Some of you might be saying “Duh! That’s what they’re for!”.

Well, let’s think about that for a minute:

You need a language construct so that your IDE can help you hide your big messy code block from you (because it’s just so hideous, you don’t even want to look at it anymore)?

If your code is so bad, that you just want to shove it under the covers, then I would argue that your design and the solution to said design is too complex.

Most of the uses I’ve seen of regions are to group member fields, constructors (and related overloads), methods and properties together. This has to be the most retarded way to use a tool because you have other tools to perform this same function. Granted not everyone can buy Resharper, but the File Structure window provides all that same information. Heck, if you simply followed a simple code standard such as:

class <className>
{

  private members
  constructors
  properties
  methods

}

this would do the same job. Honestly, if you can’t LOOK at your code and tell a constructor apart from a property or field, then you should be looking for a different line of work. Please, stop commenting the obvious!

Now, you will eventually get classes that are thousands of lines long, however there are other constructs in the language that can help you keep things neat without using this lame excuse for a preprocessor tag. When you DO find your class encroaching on this large line number threshold, that is a prime time to look at your code for copy/paste refactoring tragedies and do it right. It might be a little painful now, but it could be the thing that saves your project in the long run.

Another lame way I’ve seen regions used is within a method. Usually there is a large block of setup code that is copy and pasted all over the place, with the same region tags. C’mon people, at that point, read about the Extract Method refactoring and actually REUSE that block of code intelligently!

I honestly can’t think of any reason to use #region tags because all the things they are hiding is just really bad code. When you start to just hide bad code, you are less inclined to go back and refactor it properly.

Let’s try this analogy: if you were looking to lose weight before the summer beach season, the best thing to do is get a mirror. This way, you will be re-motivated on a regular basis.

The mere act of having the bad code stare back at you will make sure that it is at least not forgotten. Nearly all codebases have some code that is not koesher. Let’s try to make that lump of code as small as possible. By then, you may even find a way to get rid of that eyesore (and system-sore) all together…after all, it was probably some hack anyway.

About these ads

81 Responses to “Just say No! to C# Regions”

  1. Dmitri Says:

    This is arguable: not all programmers are capable of remembering all they wrote. When you give code to someone else, it makes it easier to read and explore the code.

  2. Frank Says:

    Somebody who goes on and on about how bad somebody else’s code must be if they use regions must have their own issues. Some people might just like to organize their code differently than you do, shut you mind off for a second and just accept a simple concept. If we all had three weeks to work on one method, we could all have really neat code… most of us don’t have that kind of time to get things done.

  3. Anonymous Says:

    For those dumbs who write a few line of codes it is not usefull. Try to write a REAL program someday without regions and try to read it some months later…

    Why don’t you get a real program like RunUO (www.runuo.com) and try to understand what the regions are for, dumbass!

  4. Anonymous Says:

    Whoa…i guess I’m the only other commenter that’s heard of self documenting code…

    Everyone is always in a hurry, and everyone makes a mess as they go along. However, if you practice good techniques, then you will end up with less mess in the end.

    It seems there are only one type of coder (never mind, developer) responding to this post: those with methods longer than a screen of text. This post is valid if you have short, self descriptive methods, that have few, if any logic branches. But, still, the point of the post seems to be that regions are abused, like any other language construct (if the only tool you have is a hammer, then every problem you see is a nail).

  5. Al Says:

    Yeah, I pretty much disagree with everything you said. Using regions to hide ugly code is clearly stupid. However, I like using regions to segment class files as you outline above (fields/constants/private member level shit) / ctors / properties / methods.

    I don’t agree with your strawman arguments either. Of course I can tell a property from a method, and I do organize my class how you describe. But I like a bit more organization.

    I also order my methods by scope and then loosely by name. That’s probably overkill, but I like to quickly be able to see the public API for a class.

    On a large project, the class viewer can get very tedious to use. I’d rather just go to definition, open the class and have the code nice and tidy.

    Do you dislike that VS.NET lets you collapse and expand method headers and definitions? In my opinion, that’s all I’m doing with regions: enhancing readability.

    I also disagree with your statement “stop commenting the obvious.” I agree that code should be self documenting, but what’s obvious to me may not be obvious to the developer following me.

    Good code organization is a hallmark of a professional developer, in my opinion. It’s obviously most important to have small, testable methods, but an eye towards readability is also important.

  6. BrianW Says:

    Any time I write an application that I know is going to be modified by someone like you I wrap each individual line of code in its own region. Also, I’m always sure to write several comments describing what each of those regions do as well as what thoughts I might be having at that moment.

    Obviously I’m kidding, but lighten up! Regions aren’t the problem, lazy programmers are.

  7. Gavin Says:

    I think you are all a bit out of order … I work on real world applications and have written millions of lines of code in my life time. I have to agree with the author of this article. There is absolutely no excuse for a region. If your one class is so long that you have to use them to navigate it, it is probably begging for a good refactor. Lengthy classes or methods are probably doing too much for anyone but the origional author to understand and no amount of regions will solve that problem, evolving it into a good design through TDD and Refactoring by using ReSharper is probably something you should take time to learn and put into practice. Comments tend to lag behind as code changes, if you rely on comments to tell you what code is doing there are some good beginner level courses I could recommend for teaching C#. Code is self explanitory, comments are not. Maybe you should give examples of your code’s usage by implementing tests not saying it works like so, when in fact this is not always true.

    • paul Says:

      Can’t help replying… even though this post is from three years ago.
      I think you are out of order: there are absolutely plenty of good excuses for using regions.

      Some of you region-haters no doubt have legitimate complaints. One guy complains about nested regions, which I have never seen and hadn’t considered, but I think I would stay away from them. Perhaps the reason you hate regions so much is because you’ve had very bad experiences with them. But the examples the author gives in his post don’t convince me regions are all bad.
      Even for hiding ugly code, I agree it’s preferable to fix the code, but how long does that take and how long does it take to surround it with a region to avoid looking at it all the time, since I don’t have the time to touch it anyway? If it was my own code, I would organize it from scratch, but I can’t be fixing others’ code all the time… who’s going to do all the testing? Who’s going to accept responsibility when my re-coding results in a production bug that wasn’t there before? My clients don’t give a flying frick about what the code looks like, all they care about is what the application does.

      What is up with the “bad code” or “refactor” argument that you region-haters keep spouting? Do you have time to refactor and/or re-write this application’s legacy code, and then test the entire app for regression bugs? Because I sure don’t. It would require a technical build (release), which the business team would never allow.

      Sure, if I’m writing a new application from scratch, I would not use regions because the code would already be relatively well organized, depending on how rushed I was. But how often in the real world does only one person write the code? The app I’m working on has had scores of developers working on it for the past eight to ten years, and none of them have had time to write proper code (I’m giving the benefit of the doubt: some of them may have just been bad coders or didn’t understand object-oriented principles, or whatever).

      In theory, maybe you have a point, but in practice, I think you’re clueless.

  8. Gavin Says:

    Anyone know of a utility which does exactly the opposite of Regionorate? I want something that can run over a solution and strip regions out?

  9. James Nies Says:

    I personally like regions for breaking code files into groups of members by construct type (like chapters in a book) and went so far as to create a tool to automate doing so. NArrange will group members into regions and can also apply sorting by name, accessibility, etc.

    Realizing that there are many teams who don’t use regions, the most recent release allows region directives to be disabled. See Daniel Root’s post for more info.

    Gavin, perhaps this would help you: If you’re not interested in sorting elements and just stripping region directives, you should be able to just use an empty elements configuration and the tool will write the members back to the file in the order they are encountered (more here).

  10. James Nies Says:

    I personally like regions for breaking code files into groups of members by construct type (like chapters in a book) and went so far as to create a tool to automate doing so. NArrange will group members into regions and can also apply sorting by name, accessibility, etc. http://narrange.sourceforge.net

    However, realizing that there are many teams who don’t use regions, the most recent release allows region directives to be disabled. See Daniel Root’s post for more info. http://blog.lifecycle-solutions.com/NArrange++Take+2.aspx

    Gavin, perhaps this would help you: If you’re not interested in sorting elements and just stripping region directives, you should be able to just use an empty elements configuration and the tool will write the members back to the file in the order they are encountered. See http://www.codeproject.com/KB/codegen/narrange.aspx?msg=2579903#xx2579903xx


  11. “Honestly, if you can’t LOOK at your code and tell a constructor apart from a property or field, then you should be looking for a different line of work. Please, stop commenting the obvious!”

    Amen to that. And if you like to see a grouped and sorted overview of the members of a class, maintaining that manually is a waste of time. It should be automated.

    One possibility is to make a tool that rewrites the source code grouped how you want it, but that means if you change your mind about the most convenient grouping style, you have to rerun that tool. The result is that a lot of changes are made which are purely cosmetic (hopefully) and so if you want to check that file in and you have to merge it with someone else’s changes, it’s going to be hard work!

    So I thought: why not just write an Add-in that produces the grouped/sorted overview on the fly, without modifying the code at all? That way you can change your mind about the order and style of grouping.

    So this is what I came up with: http://www.codeplex.com/ora

  12. Jim Barritt Says:

    Absolutely agree with the author of this article.

    If your method or class is so big you need to fold the code to hide it the answer is simple. YOur method or clas IS too big. RTefactor it into smaller, more cohesive methods / classes and your region will disappear.

    Infact your region is probably already telling you the name for the new class..


  13. LOL…things like TDD, Dependecy Injection, OOP vs Functional I can see as being debatable and could add value to product.

    However, while people are debating things like REGIONS and code formatting in their code. Others are making millions from writing applications like Digg or the fart application on the iPhone.

    So, you can have the cleanest code without regions with Resharper or you can get some sanity back into designing software.

    Note: I think after Agile methodologies took off. Some people were banking 20k/week teaching it like it was a Bible in organizations. Other nonsense like this took off for “best code organization practices”. Off course resharper/coderush jockies will push that regions suck, because they have a tool that makes things colorful and pretty :)

  14. Valamas Says:

    Regions bad. When there are too many nested, the collapse and expand macro does not show me all i want.

    LOL, i have a macro that removes regions (suck that!). If you need regions, you have coded badly. Consider sorting and spacing you code better or using a partial class structure.

  15. Rod Furlan Says:

    I use regions to hide great code :)

    Either I am an outlier and you are partially wrong or I am not an outlier and you are completely wrong. Either way your claim is falsified.

    (Try to avoid absolute claims because they are too easy to falsify)

  16. Anonymous Says:

    -Sometimes, I simply like to work on several methods at the same time. Regions help you do this a lot faster since you can bring the code closer togother.
    -Even though a function should never be a screen long, you can easily have multiple functions covering similar things. Having them grouped together allows you to have a better birds-eye view on the application.
    -Relying on fancy tools is never a good idea. Most simple text editors know how to handle a construct like #region.
    -Clearly, you still have a lot to learn about coding.

  17. Bragi Says:

    -Sometimes, I simply like to work on several methods at the same time. Regions help you do this a lot faster since you can bring the code closer togother.
    -Even though a function should never be a screen long, you can easily have multiple functions covering similar things. Having them grouped together allows you to have a better birds-eye view on the application.
    -Relying on fancy tools is never a good idea. Most simple text editors know how to handle a construct like #region.
    -Clearly, you still have a lot to learn about coding.

  18. Mathias Says:

    Jeff Atwood does not like regions, either:

    http://www.codinghorror.com/blog/archives/001147.html

    And, to Bragi’s point, if you prefer to group together methods/properties, and really want keep them in one class, partial classes can do the job nicely. That being said, having this type of issue often indicates that your class is getting too big, and that it’s time for some refactoring…


  19. Ctrl + M + L and all your problems go away :)

    Now seriously it like saying “Don’t like Red.” It is something totally subjective and differs from developer to developer.

  20. Philipp Says:

    Regions are a construct you *may* use to organize your code no matter how many LOCs you have, and that’s it. I really don’t see a correlation to bad code there and saying that anybody who uses regions must write badly structured / bloated / ugly code is just plain wrong.

    Just my 0.02%


  21. [...] Just say No! to C# Regions « public abstract string[] Blog() [...]

  22. Valamas Says:

    Hi John, RE the region collapse and expand commands.

    I know these commands very well. However, when some nutty programmer or ORM tool makes lots of nested regions, these commands do not work.
    Ctrl + M + L does not expand enough
    and
    Ctrl + M + O over collapses

    The panic button is Ctrl + M + P. That is no fun when the class is 10,000 lines. Bad bad programming.

  23. Paul Says:

    Dude, you need to chill out. I use reagions just for organizational reasons, plus my xml comments take up alot of space. You do document don’t you?

    Not sure partial files are the solution for large code files. I usually go by home much fills up a screen.

    So would you not hire great programmers because they like to use regions – which don’t impact anything but your eyeballs?

  24. Phil Betjeman Says:

    That’s a really odd thing to rant about. I use regions because I can use them as easy hook points for macros (and I have a macro to write the region code in the first place).

    Ranting about bad code is one thing, but ranting about something which has no effect on the compiled code and is purely down to user preference? They’re very easy to ignore and if you hate them that much you can always set the font colour to the same as the background colour and wham, never have to deal with them again.

  25. Anonymous Says:

    how stupid


  26. [...] Just say No! to C# Regions and I still say Regions are not useful… but… (Saul Mora) [...]

  27. Sean Says:

    It’s amazing. The comments that are against regions automatically assume that the rest of us don’t know how to organize code or write self-documenting code. I haven’t just been looking at a lot of code for the past (as the author of this post mentions he has been doing). I’ve been looking at code for many, many years. It has been my general experience that individuals that use regions are much better at organizing code than individuals that don’t use them. It is my belief that regions help to create a layer of organization, whereas I’ve observed that non-supporters tend to throw in methods without any particular order.

  28. Timm Says:

    As a disabled programmer, I must say that regions are incredibly valuable for reducing and hiding complexity, and dramatically improving the ability to navigate a large source file, especially for those like me who physically struggle to use a computer.

    It seems like every 6 months some blogger is condemning regions. But regions are just another tool like the IDE, Intellisense, XML formatting, object and class browsers, refactoring, etc. Not every tool will offer the same utility to every developer. So it’s not wise to condemn a tool whose utility you fail to grasp but yet is invaluable to others.

  29. Saul Says:

    Thanks for all your comments. Everyone has great opinions on both sides of this argument! I will have to admit, that when I wrote this post, I was in an evil corporate job, and I ran into lots of evil code which was “fixed” with the use of regions. Heck, I remember seeing a blog post by Ayende (http://www.ayende.com/blog) telling about how he witnessed first hand the practice I most despise regarding regions: sweeping code under a rug. I think that was the tipping point to author this post.

    Don’t get me wrong, code folding, and very useful feature in a text editor or IDE, is GREAT. Comments are useful too. But, alas, everything should be done in moderation, and I have seen #regions become far overused for evil than for anything truly useful. Assume that the readers of your code understand the language of the code (otherwise, why should they even be there reading it?). That means those default regions (lke contructors, properties, etc) can go away. As with any language tool, overuse is smelly code, that should be refactored, and regions are no different.

    I find IDE related language constructs bad in any language, that is just my preference. Dabbling in Obj-C lately, the #pragma construct has similar abilities. I don’t really like this either, but I have not seen it as overused and poorly used as #regions in C#. Ruby doesn’t have this construct at all. I like that the code is more or less self documenting, eliminating lots of duplication.

  30. Arun Says:

    Strongly disagree


  31. “So would you not hire great programmers because they like to use regions – which don’t impact anything but your eyeballs?”

    YES! I would NOT hire someone that insists on the value of regions. This means that they feel they need regions. And, if their code needs regions, it’s sure to be poorly designed. And, if it’s poorly designed, it’s hard to maintain. And, if it’s hard to maintain, then it won’t be providing good ROI moving forward.

    If these statements anger you, then you should ask how someone could possibly have these views. You can either write those of us off that hold these opinions, or you can look into it.

    Feel free to flame me directly via Twitter at @eric_anderson

    Bring it on.

  32. Timm Says:

    “And, if their code needs regions, it’s sure to be poorly designed.”

    That’s simply not true. C# regions are meta tags that have no effect (good or bad) on the design of the software. They are a source code FORMATTING tool that helps programmers organize and navigate code files.

  33. Mark Says:

    Agreed with the author.

    Stop using regions! you will survive without them.

    Once you get used to life without regions you’ll write your own post similar to this one..

  34. Max Says:

    Re: Stop using regions! you will survive without them.

    Why would I want to “survive” without them? That’s like saying “stop using an IDE, you’ll survive without it.” Of course I could, but why would I want to take such a big step backward in productivity? I could also forgo the keyboard and mouse and revert to punch cards. How silly.

    Re: Once you get used to life without regions you’ll write your own post similar to this one.

    I already got used to life without regions — that’s what programming was like from 1985 to 2001 when I discovered C#. But once I saw how I could collapse a 20-page source file into a single page, I was hooked. Why would I want to go back?

  35. Blub Says:

    Agree! Who came up with the idea to regionize based on protection level? Seriously…i can understand that you want to put code that works together in the same region but this is definitely not the case for methods with same protection level.
    Just compare these two blocks:

    #region private stuff
    private void RenderX()
    {…}
    private void PlaySoundX()
    {…}
    #endregion
    #region public stuff
    public void RenderY()
    {…}
    public void PlaySoundY()
    {…}
    #endregion

    ———————————-

    #region rendering stuff
    private void RenderX()
    {…}
    public void RenderY()
    {…}
    #endregion
    #region sound stuff
    private void PlaySoundX()
    {…}
    public void PlaySoundY()
    {…}
    #endregion

    Both these snippets are bad because they should be refactored but if we disregard that for a moment, which one makes most sense? This gets even worse when we start to add properties and variables.
    I can’t understand why anyone would like it this way but still there is so much code that looks like this. Ghaa!!

  36. Mark Says:

    @max – Try reading the post again, or even http://www.codinghorror.com/blog/archives/001147.html

  37. Tim Scott Says:

    Sad to say most code I see today is procedural rather than OO. The result is large classes, long methods and deep nesting. With OO it generally never occurs to you to use regions. Still even with procedural code, Resharper makes moot whatever benefits regions may have offered. The big problem I see with regions that over time they are made liars — i.e. public methods found outside the public methods region.

    With regard to comments, comments that explain what the code is doing indicate a code smell. Comments should say why, not what, and there should be very few that you need to explain why. The exception is XML comments in for framework. However, when you decide to add XML comments, you should be sure the whole team is forever committed to this extra maintenance effort. A comments that lies is infinitely worse than no comment at all.


  38. wow , I would say the you have some real issues with regions. I am pretty ambivalent to them really, if they are there I deal with, if they’re not I deal with it. I can’t say I have spent much time really worrying about them.
    They’re like eveything in your tool set, they have to purpose and place in life.

  39. Valamas Says:

    – REGION REMOVE MACRO IS HERE —
    Map this baby as an icon on your visual studio toolbar.

    Sub ClearRegions()
    DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
    DTE.Find.FindWhat = “^:b*\#region.*\n”
    DTE.Find.ReplaceWith = “”
    DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
    DTE.Find.MatchCase = False
    DTE.Find.MatchWholeWord = False
    DTE.Find.MatchInHiddenText = True
    DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
    DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
    DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
    DTE.Find.Execute()

    DTE.Find.FindWhat = “^:b*\#end region.*\n”
    DTE.Find.ReplaceWith = “”
    DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
    DTE.Find.MatchCase = False
    DTE.Find.MatchWholeWord = False
    DTE.Find.MatchInHiddenText = True
    DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
    DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
    DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
    DTE.Find.Execute()
    End Sub

  40. sth_Weird Says:

    I love regions, I wish other programming languages had them. Of course they can be used to hide bad code. But that’s not what they are supposed to be used for. In real life you can use boxes to sort your things or you can use them to to just stuff anything in them you quickly want to hide from view. Do you say we should not use boxes, just because some people use them the wrong way?
    They are a great way to organize you code. I love grouping my code with them, I like regions for my declarations, constructors, functions, properties,…of course I could use partial classes, but I do not want to jump from one file to another, or have hundreds of files for one class. And sometimes when you have a complex program you have a lot of code. Yeah you can always try to put parts of it in different classes, but if it all belongs together and you have to share variables you’ll have to put loads of paramters into the external classes, and once again you multiply the number of files (sure, that looks very impressive!). Don’t get me wrong, I hate unstructured code, I do not like it when people put it all in one class when it is crystal clear that parts of the code could be reused.
    BUT classes should be used for this and this only and not to make code easier to read. That’s what comments and regions are for!

  41. Ed Says:

    Wow, what a picky ass article! I agree I have seen a fair use of inappropriate region use but dropping regions all together is just plain stupid when you write huge programs.
    I write games in XNA game studio in C# and regions help to group things together in classes. One region contains the methods for loading and drawing the games sprites (graphics) while another contains the code for setting up the game’s interface and loading the appropriate settings.

  42. Matt Says:

    Disagree, completely.

  43. Florian Haag Says:

    Hi, I’d like to state that I do consider #region a good way to topically structure your code.

    First of all, regions are not despicable because they group code only along one dimension – all of our structures do this. You can put your properties into business-related objects (car, plane) and might thereby lose the grouping by subsystem (images, sounds) or you group them into subsystem objects and thereby lose the connection to business objects.

    I would like to remind some of the commenters here that OOP is not only about tearing code apart into tiny rags, but also about grouping things. At some point, you’ll have to connect different parts of your code and 100 classes with two methods each are simply not any better than two classes with 100 methods each. You could even argue that while an oversized class at least gives you a list of all methods you can search through, you are absolutely at a loss once you have to navigate through an unknown 10-leveled object hierarchy because everything had to be broken down into tiniest bits.

    The goal should always be a fair balance between modularity and maintaining the class landscape in a way that other developers can still grasp it without memorizing hundreds of interconnected classes. This means, the size and the complexity of the resulting modules always has to be considered, too. Take, for example, the code snippet provided above by Blub:

    #region rendering stuff
    private void RenderX()
    {…}
    public void RenderY()
    {…}
    #endregion
    #region sound stuff
    private void PlaySoundX()
    {…}
    public void PlaySoundY()
    {…}
    #endregion

    He or she claims that this is bad code and must be refactored. I tend to disagree. Without knowing what the rest of the class as well as the implementations of these methods look like, I can imagine situations both where a refactoring is badly needed as well as where a refactoring would not be any helpful.
    The need or willingness to categorize need not even mean many lines of code. 30 lines can perfectly contain six methods which logically belong directly to the containing class, yet which for another reason – “along another dimension” – can be categorized into two groups.
    I would like to ask the author of the comment for a more complete example here.

    It has been frequently mentioned that if a class gets too long, it should be broken down into several pieces. Truly, often there is no choice about the length. Once you implement a somewhat bigger interface such as System.Collections.Generic.IList, your class will inevitably have many methods. If you only offer read-only access, half of them will only throw NotSupportedExceptions, so these methods are not needed, but have to be there. While this may still be attributed to bad design of the System.Collections.Generic namespace, where interfaces such as IList should inherit from others that only feature the respective read-only members, you again get many methods once you implement IList more than once (for different Ts).
    For your information, I do consider it definitely good practice to add as much support for standard interfaces, wherever possible.

    One last issue I found somewhat funny in the above comments is when some commenters stated that “regions are bad because you can do the same thing with partial classes”. If you condemn regions for their capabilities of hiding (too) large blocks of code and leading to huge classes, wouldn’t partial classes be even worse? Not only do they put the “hidden” code completely out of sight of the programmer – as opposed to regions, which are still in the same file (and editor tab) -, they even lead to the creation of seemingly well-structured units (a collection of similarly-sized files) at design time, yet the compiled result will be a huge class again.
    In fact, partial classes are just another organizational level which has no further significance for the compiler, right above the region level.

    As a conclusion, while regions can of course be misused – as about any other language feature -, I cannot agree with the statement that they are generally the reason or a signal for bad code.

  44. Mark Says:

    Wow… This dude probably never worked in an enviorment with multiple programmers. Regions are handy, messy code or not. Regions are beneficial, use them or don’t. They make code easier to read and troubleshoot.

    This article is somewhat asinine.

  45. Hendrik Says:

    Regions are BAD!!!

    For around 5 years I used to enjoy meticulously organising every code file into regions. Even my elborate report methods had regions for “create report”, “create headings”, “create totals” etc.

    Then I saw the light…

    These days, there is no greater irritant to me than opening a fellow developers code file and see a closed bunch of regions.

    I believe that any code group not visible in one screen is generally bad design.

    When all my properties, constructors and methods collapsed, is not visible on one page – likely my class is doing more than one thing.

    If my method’s longer than 10-15 lines of code, it’s 99% of the time bad design. Time to freshen it up!

    There are exceptions to every rule, but the last time I used a region was for a very bad 100 option switch statement. A delegate dictionary built from an embedded resource text file sorted that one into very elegant code.

    There is always a solution to keep code short and simple, without resorting to regions.

  46. Michel Says:

    In my experience, despite all philosophy and all wonderful world perfect code talk, when you have lots of developers working on the same code and probably writing not so beautiful code, the regions can help to put some order in the chaos.
    Sometimes we need to look at the bad code and live with that for a while or anybody has plenty of time for refactoring?

  47. Andy Says:

    An interesting read, and while some things doe with regions are stupid, there are some uses to them too (like everything really).

    I wrote a follow up here about it:

    http://www.stormbase.net/region-hate

  48. Eldon Says:

    Regions, like any other part of C# have thier place. I use them quite offen and I have very organized, commented & clear code.

    I use regions to help quickly fine code and to cut down on scrolling. Also, if do correctly, regions can improve the readablility of your code if someone else has to look at it.

    I have been programming for over 30 years and regions are one of my favorite tools.

  49. Steve Says:

    I too have been programming for nearly 30 years. Regions are good. Agreed, they can be redundant if the code is short.

    It is easy for someone, who rewrites someone elses code, to be a code critic.

    To all you aspiring programmers out there: Program structure is an art, so develop your own style. Take advice at face value. And always beware the critic.

  50. Jeff Says:

    I generally have the same oppinion about regions and only tend to use them in situations where they make sense. Below are some examples of where I can tolerate them.

    * Group the accessors and static property for Dependency Properties. Since I generally only create a dependency property once and then rarely need to see that hideous yet required code I like to put a region around each with the name of the property.

    * Grouping auto-generated code which doesn’t follow the newer partial class concept. This really isn’t much of an issue though anymore unless you work with .NET 1.1 code.

    Also I think ordering conventions of members in a class can be quite tricky especially with concepts like Auto-Implemented properties and Dependency Propertys. Also with source control things get messy when you have to move a member because it’s access level or name has changed.


  51. [...] haters; Why all the fuss? I hear a lot of programmers saying #regions are a code smell. From programmers I’ve never heard of to celebrity programmers, while the development community appears to be passionately [...]


  52. [...] Do you say No to C# Regions? May 26, 2010, 11:53 pm The idea behind the question is – Just say No! to C# Regions [...]


  53. [...] Just say No! to C# Regions [...]

  54. Miguel Correia Says:

    Programming in C# since it’s early days and after having had the pain of trying to read code abused by regions and after not really seeing their point, the less I like regions. They do give the illusion of a better organization, but in fact the only thing they are doing is highlighting the organization you already have to have. Anyhow, good use can be helpful. The problem is, either I’ve been very unlucky, or statistically, most of the use I’ve found in regions is to enable slacky developers to hide their crap and to create a false sense of organization. I started hating regions from the day I saw a method with over 1000 lines and divided in regions. Didn’t the author ever hear about methods? You don’t even need resharper to refactor into submethods. Visual Studio does it for you. The problem is, that crap was absolutely unreadable and the promoted form of code reuse was copy-paste… loads of code segments repeated here and there, whereas had the author used method, it would have become more intelligent. Now, if this were an isolated case, I wouldn’t feel so much against regions… But no, it is much more often than one would expect.

    Bottom line, even though I wouldn’t outlaw regions themselves (just because I don’t use them myself, doesn’t mean there is no good use for them – there can be exceptions… few… very very few), if I were the “C# owner”, I would certainly forbid them inside methods with a compiler error.

    There is absolutely no place for regions inside methods!!!

    • Anonymous Says:

      “They do give the illusion of a better organization, but in fact the only thing they are doing is highlighting the organization you already have to have”

      When you consider collapsibility of regions you can see they do have very real impacts on the organisation and readability. It is undeniably easier to locate code of interest within an appropriately regioned file compared to a non-regioned created with the same organisational structure. My productivity within my code bases has certainly improved quite a deal since I’ve started using regions more extensively (I even nest them all the time) entirely due to the improved ease of which I locate the areas/pieces of code I’m interested in working on (and no I never had any trouble before hand without using regions, they have just made things easier).

      “I started hating regions from the day I saw a method with over 1000 lines and divided in regions. Didn’t the author ever hear about methods? You don’t even need resharper to refactor into submethods. Visual Studio does it for you. The problem is, that crap was absolutely unreadable and the promoted form of code reuse was copy-paste… loads of code segments repeated here and there, whereas had the author used method, it would have become more intelligent. Now, if this were an isolated case, I wouldn’t feel so much against regions… But no, it is much more often than one would expect.

      There is absolutely no place for regions inside methods!!!”

      That is a poor excuse that has nothing to do with any inherent issues with regions themselves but rather is entirely related to how the code author has used regions. While I agree the example you paint is bad I really disagree that with your opinion that regions don’t belong in methods, there could be times (however rare they may be) where it may not be really suitable to split the code up into different methods. I’m guilty of using them within methods before myself within a GUI library which created control graphics at runtime with the supplied style, a single method contained the logic for rendering the different parts of the control (segregated into regions to tell them apart, some were fairly big so region code folding was useful here too) which was unsuitable for splitting into different methods due to their interconnectedness, extensive use of local variables and performance concerns. Just because you may not find a use for them within methods doesn’t mean no one else can, to say they don’t have any place there is nothing more than an extremely biased subjective opinion.

  55. Rj Says:

    #regions are a tool that can be used for good, and surely you ( the reader ) think you are.

    Unfortunatly, I see the whole programming community taking a turn for the worse.

    When I open a file with 10 regions do you think I bloody want to click on them all to see what the fuck the class contract is.. NO. I #$#%(# dont.

    Go resharper yourself in the throat.

    • Florian Haag Says:

      I think it is funny how you and others reduce regions (a language feature just like comments, but where the compiler checks whether they form a well-formed hierarchy) to an IDE-specific way to handle them, namely to automatically apply code-folding. I use regions a lot because they help in organizing code. I don’t really care about whether they can be folded away or not, because that’s at best an extra feature adding to the concept of regions.

      But even if we assume the regions are folded:
      Your problem description about the file with 10 regions, on the other hand, sounds as if those regions are untitled. Usually, you don’t have to open all the regions when you’re looking for something specific, because the region title tells you about what’s found inside which region. Of course, if that’s missing, that’s a bit of a problem … which is why I’d support a compiler rule to enforce titles for regions.
      However, if you only want to see the complete public interface of the class, I think the code’s the wrong place to look at, anyway. That’s what automatically generated help files (e.g. using Sandcastle) are for.


  56. Great weblog right here! Additionally your website lots up very fast! What web host are you using? Can I am getting your associate link for your host? I wish my site loaded up as fast as yours lol


  57. Great work! That is the kind of information that should be shared around the net. Shame on Google for not positioning this submit upper! Come on over and consult with my site . Thanks =)

  58. Anonymous Says:

    It seems you’ve never wrote programs that exceed 1000 lines.
    Regions are very usefull to group together different functions that refers to the same use case or the same functionality.

    Because if you have more that 1000 lines of code, and no regions, I don’t want to be your mouse scroll wheel ;-)


  59. [...] and against arguments on the topic. If you want to get enlightened(?) on this topic, check here, here. This post is not about discussing whether you should or should not use region, this is only about [...]

  60. net grid Says:

    Dapfor provide a excellent tutorial for c# more help you can visit there dapfor. com

  61. hfrmobile Says:

    To keep it short: Regions are out-of date. In .NET 1.0 and 1.1 they were used to hide (ugly) generated (huge) code blocks. Since the partial keyword was introduced regions are obsolete!

  62. Anonymous Says:

    I like to look at my code, I am proud of my code, but I still like to organize it using regions, I never use region inside a method.

    • hfrmobile Says:

      You’re claiming that you’re proud of your code but posting here as “Anonymous”!?

      If there is a need to organize your code using regions then there is something wrong with your code/design (e.g. god classes).

      There is no excuse for using regions maybe except one: When a class implements interfaces (e.g. IDisposable) then it is OK to wrap that implementation within a region called “IDisposable implementation” …?


  63. [...] The idea behind the question is – Just say No! to C# Regions [...]


  64. Can I just say what a relief to uncover somebody
    who really understands what they are discussing on the web.

    You certainly know how to bring a problem to light and
    make it important. A lot more people need to look at this and
    understand this side of the story. I can’t believe you aren’t more popular
    because you certainly possess the gift.


  65. Hey There. I found your blog using msn. This is a really
    well written article. I’ll be sure to bookmark it and return to read more of your useful info. Thanks for the post. I’ll certainly return.


  66. […] The idea behind the question is – Just say No! to C# Regions […]


  67. […] reading Just say No! to C# Regions I’d like to find a Visual Studio 2008 add-in that will reorder my class members […]

  68. Zeb Fross Says:

    I totally agree! Regions are a terrible practice! They sound good at first, but they are only used to hide big, messy code. I want all my code visible to show off its elegance.

  69. Johnc941 Says:

    When choosing the colours for you office, there are a few basic points to consider. aeedaeafdada


  70. […] The idea behind the question is – Just say No! to C# Regions […]


  71. Howdy! This is kind of off topic but I need some advice
    from an established blog. Is it very hard to set up your own blog?
    I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about creating my own but I’m not sure where to
    begin. Do you have any points or suggestions? Appreciate
    it


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: