Thursday, September 22, 2011

Removing the dreaded #regions using Visual Studio

Back when .NET was released in 2001, the #region/#endregion feature seemed like a good idea at the time. I think it was more a novelty than anything.

If you are a seasoned .NET developer you will probably know what #regions are and how annoying they can be (or you might support them, shame). For those who don't know what they are, this MSDN page might help explain #regions a little:

There have been many posts about #regions over the years. There was one I was reading recently that claimed #regions are a sign of code smell! That is pushing it a bit, they are not code smells but are very annoying and if I used #regions it might say something about my code. It might say that I write large bloat god type classes that need regions to split it up in order to maintain it more easily - that you could argue could *potentially* lead to a code smell.

When I open some source code file, often it will not be my code or sometimes it might be. Lets assume its not. Lets also assume that the developer of that source code like regions. The first thing I get is the screen shot below:

Figure 1: God class with regions and outlining feature turned on

So now in order to understand this GodClass, I'm going to have to expand all those regions as I didn't write this code. All I want to do is get at the code to understand it, these #regions are preventing, or rather, making it more difficult for me from doing so.

The title to this post reads "Removing the dreaded #regions using Visual Studio". So if you're in a shop that loves to use #regions or your code base is such that to remove all the #regions would be weeks of work, fear not! I didn't know this feature existed in Visual Studio up until a couple of days ago but you can actually turn off the *outlining feature* that makes #regions possible.

To turn off this feature do the following:

  1. In Visual Studio click Tools -> Options
  2. In the options tree view, click Text Editor -> C# -> Advanced
  3. Then untick option Enter outlining mode when files open (see figure 2 below for an example)
  4. Click OK
  5. Enjoy!

Figure 2: Turning off #region support in Visual Studio

As far as I am aware there doesn't seem to be support for this if you're using VB.NET. This only seems to be a C# feature right now.

So now if I load the GodClass in Visual Studio, I get the following source code:

Figure 3: Outlining turned off

It's not perfect I admit as the regions are still there, but at least I can now see the code without having multiple mouse clicks in doing so...

1 comment:

Unknown said...

Great tip. Regions annoy the heck out of me.