Recently I have been confronted with a movement that seems to hate using #Regions in source code files. Personally I really like using regions and I absolutely like the ability to collapse sections of code I am not directly working with. The opposing argument I am given is that my classes or methods must then be too long. I really have to disagree, I work hard at making my classes, methods and properties as refactored as I can get them. But I do like to organize my code into related sections. And sometimes there is just a lot of logic that goes into creating the UI or business logic and regions help keep things clean.
I wanted to show an example from a custom Exception class I was creating today. It consist of two custom properties, PropertyName and PropertyValue. I wrapped these properties into a region and moved them out of the way. Once I have the properties created there should be nothing else I need to do with them and by wrapping them in a region I can hide them out of view.
This reduces the amount of code that I need to slide through to get to code I am working with at the moment. It also forces me to organize my code into common areas or ‘regions’. This alone is worth it to me because it gives me a nice way to toss my code into a bin of sorts to keep it organized.
The next region I created is to hold my constructors. Because this is a custom exception class I created three new constructor overloads. This gives me the ability to set my custom properties and call the base constructors for the Exception class. Again I have all my constructor overloads contained within one area in my file and I can expand and collapse it as needed.
What are my alternative choices? Creating several classes that either inherit from a base class or create numerous partial classes with partial methods. Each of these hold their own merits but to me serve different purposes from what regions are designed to do in Visual Studio.
I invite those with opposing views or that can add to the case for using regions to please leave comments on the topic. This is a small class where I show how I really like to use #Regions. There is not an overwhelming amount of code in this class, but the #Regions help keep things organized.
A special note, I have CodeRush and Refactor Pro from DevExpress installed on my machine. This makes the display of the regions look different than the out of the box look. The functionality is still the same, but I just wanted to point that out if you were feeling a little lost.