I am often working with a large legacy code base. Within this code base there is a massive usage of regions. There are nested regions and even more painful, regions in methods.
I think it’s best to show a simple example:
public bool Insert(int loopId, string value) { #region Local Variables LoopTest loopTest = new LoopTest(); #endregion #region Actions loopTest.Create(); loopTest.SetKey(loopTest.GetClientId(), loopId); loopTest.SetTestValue(value); if (loopTest.Insert()) { loopTest.Commit(); } else { return false; } return true; #endregion }
To improve the readability of this code, I wanted to remove the regions within methods like that:
public bool Insert(int loopId, string value) { LoopTest loopTest = new LoopTest(); loopTest.Create(); loopTest.SetKey(loopTest.GetClientId(), loopId); loopTest.SetTestValue(value); if (loopTest.Insert()) { loopTest.Commit(); } else { return false; } return true; }
There is some potential to improve the readability of this code for sure. For example you could use the conditional operator instead of the if-else-construct. Cleaning the entire method would clearly go beyond the scope of this article about removing regions.
After spending some time on Google, I haven’t found any program to automate this process. Therefore I wrote a tiny program myself.
RegionRemover
RegionRemover is going to remove all the specified regions from your entire code base. You can configure which regions you want to remove and which regions you want to keep in your code.
A sample call
RegionRemover.exe "D:\\_SVN\\MySoftware_Trunk\\" "Local Variables" "Actions" "Window Variables" "Fields"
- The first parameter specifies the root directory of your source code. The program will recursively search for any .cs files within that directory.
- Any further parameter specifies a region which will be removed.
In my example above the program will start exploring the file system at D:\_SVN\MySoftware_Trunk\ and will remove any from the following regions: Local Variables, Actions, Window Variables and Fields.
Download / Source Code
I decided to release that tiny piece of software as open source. You can find the source on Bitbucket. As I wrote earlier on this blog, I recently moved my entire source code to Bitbucket. It’s written entirely in C# and doesn’t use any third-party libraries.
Update December, 12th 2018: The source code to this blog post is no longer available.