Skip to main content
Published on

goto and #region/#endregion in C#

Share:

Introduction

C# is a language packed with features that, when properly applied, can make code clearer, more organised, and more efficient. In this article, we will explore two of these features: the goto statement and the #region and #endregion directives.

goto in C#

The goto statement is a tool that allows us to change the execution flow of a program, directing it to a specific point. Although many consider its use a bad practice, there are situations where it can be the right choice.

When to use goto:

  • In switch blocks to avoid code repetition.
  • In deeply nested loops where breaking out of an outer loop from an inner loop is necessary.

Cautions with goto:

  • Excessive use can make code difficult to read and maintain.
  • It can introduce logical errors if not used carefully.

#region and #endregion in C#

The #region and #endregion directives offer a way to organise code into visual blocks, making it easier to read and edit in large classes.

Benefits of using #region and #endregion

  • Organises and groups related functions or properties.
  • Helps hide implementation details, allowing developers to focus on specific areas of the code.

When to use

  • In large classes to group related methods.
  • To hide test or debugging code that should not be exposed in the production environment.
#region Libraries
using System;
#endregion

namespace Base {
  class GotoAndRegionEndregion {
    #region Run() Method
    public void Run() {
      Console.WriteLine($"Result of the TestGoto() method: {TestGoto()}");
    }
    #endregion

    #region TestGoto() Method
    private int TestGoto() {
      var number = 0;

      for (int i = 1; i <= 10; i++) {
        for (int j = i; j <= 10; j++) {
          for (int k = 0; k <= 10; k++) {
            if (j == 5 && k == 5)
              goto FirstLoop;
          }

          number++;
        }

        FirstLoop:
          continue;
      }

      return number;
    }
    #endregion
  }
}

Conclusion

Although goto and #region/#endregion may have their controversies, understanding when and how to use them can be crucial for creating well-structured and efficient C# code. The key lies in using these tools with discernment and understanding the implications of their use on the flow and readability of the code.

Happy coding!