One thing that annoys me when reading other people’s C# or VB.NET code is the use of regions. The main reason why anyone should wrap a piece of code inside a region is that there is something inside that they don’t want you to see. Visual Studio’s default behavior is, as you know, to collapse all regions when you open the file. Here are some of the uses I’ve seen of regions:
Grouping of Constructors
I can see the point with wrapping the constructors in a region. Usually nothing interesting should happen in the constructors. But I have been surprised many times by the code people put in their constructors. Therefore you can’t make the assumption that the constructor code is something you can ignore.
If you have so many constructors that you need to hide them, your class is too complicated.
Grouping of Private methods
The same argument as above applies to private methods as well. If you have so many private methods that you want to hide them, your class is too big. There is another class inside just waiting to be released!
Grouping of field and property declarations
Here are some simple rules to avoid many lines of property declarations:
- Avoid properties if you can. They violate encapsulation.
- If you still need properties, at least use implicit backing fields
- If you have many properties, your class is too big
From time to time I see people dividing up methods in regions, usually with some hint of what the wrapped code is supposed to do, e.g.
#region Do processing. This is the worst use of regions in my opinion. A well written method should not be more than maybe ten lines long, so there is not much room for regions, is it? Long methods are usually quite easy to refactor, especially with a refactoring tool. Even Visual Studio can do Extract Method out-of-the-box!
If you feel an urge to write
#region in your code, you should refactor instead!