Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Goto Statement in C#

Introduction to Goto Statement

The goto statement in C# is a control flow statement that allows you to jump to another point in the code. Although its use is generally discouraged due to the potential for creating complex and hard-to-maintain code, it can be useful in certain scenarios, such as breaking out of deeply nested loops or for implementing state machines.

Syntax of Goto Statement

The general syntax of the goto statement is as follows:

goto label; ... label: // code to execute

Here, label is a user-defined identifier that marks the location to which the control will be transferred.

Basic Example

Let's look at a simple example to understand how the goto statement works.

using System; class Program { static void Main() { Console.WriteLine("Before Goto"); goto Label; Console.WriteLine("This will be skipped"); Label: Console.WriteLine("After Goto"); } }

The output of the above program will be:

Before Goto
After Goto
                

Using Goto in Loops

The goto statement can also be used to break out of nested loops:

using System; class Program { static void Main() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i == 5 && j == 5) { goto End; } Console.WriteLine($"i: {i}, j: {j}"); } } End: Console.WriteLine("Exited the nested loops."); } }

The output of the above program will be:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
...
i: 5, j: 4
Exited the nested loops.
                

Goto in Switch Statements

The goto statement is often used within switch statements to jump to different cases or to a default case. Here is an example:

using System; class Program { static void Main() { int number = 2; switch (number) { case 1: Console.WriteLine("Case 1"); break; case 2: Console.WriteLine("Case 2"); goto case 3; case 3: Console.WriteLine("Case 3"); break; default: Console.WriteLine("Default case"); break; } } }

The output of the above program will be:

Case 2
Case 3
                

Considerations and Best Practices

While the goto statement can be useful, it’s important to use it judiciously to avoid creating "spaghetti code," which is difficult to read and maintain. Here are some best practices:

  • Avoid using goto for general control flow. Use structured loops and conditionals instead.
  • If you must use goto, clearly document its use and ensure the code is still readable.
  • Consider alternative approaches, such as breaking out of nested loops using flags or methods.

Conclusion

The goto statement is a powerful but often misunderstood control flow tool in C#. When used appropriately, it can simplify certain coding scenarios. However, it should be used sparingly and with caution to maintain code readability and maintainability.