c# #region Tags and Why I Don’t Like Them

I’m back to the Microsoft stack (ASP.NET MVC, c#, etc.) for the first time in a while. One of the things When I worked with it previously, I hated #region markers in any code file. Now, since I’m the lead, I have a policy of deleting them where I find them. No exceptions. I did tell my team that I would do this but I never really explained why.

The #region was originally used to segregate generated code from the code written by the developer. These days are over, partial classes totally eliminated this usage.

Today, I see two main uses of #region tags.

First, they are used to group types of things. Region tags are put around:

  • Properties
  • Public Methods
  • Private Methods

The second common usage is grouping related things:

  • Around an event and it’s delegate
  • All methods related that talk to the database

So why don’t I like #region markers?

Regions Hide Code

When a class is opened in Visual Studio, and it has #region tags, the #region tags are collapsed by default. In other words, at least some of the implementation of the class is hidden when the class is opened. This can make it difficult to find what you were looking for. And, expanding the regions can take you out of your train of thought by preventing you from going straight to what you were looking for.

Regions Hide Size

One of the more common design problems is a class that does too much. The feedback from scrolling and navigating a large class is one of the items that helps determine it is time for a refactor. Regions eliminate this feedback, they can make a class that is way too large not feel that way. But that feeling is an illusion, as soon as any serious work needs to be done, the size of the class will quickly become an obstacle to maintaining the class.

Regions Hide Complexity

The hidden code can also hide complexity. If a class is doing too much, when it’s responsibilities are muddled, regions can be used to group that functionality to make things appear more maintainable. But again, it is an illusion. Because as soon as something not insignificant needs to change, especially if that change will cross regions, the region approach will make the change more difficult.

Let’s Make Maintainable Code

One of our goals when developing most systems should be delivering maintainable code. Regions work against this.

Microsoft has acknowledged that #region tags should not be used any longer. Today, the default settings for StyleCode, do not allow #region tags to be used. In other words, Microsoft no longer believes #region tags need to be used. So neither should you.

Leave a comment