Skip to Content
Course content

173: The goto Statement and When to Avoid It

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, does C# actually have a goto statement?

It does. I know most of your tutorials probably skipped over it, or maybe they told you it doesn't exist in modern languages, but it's right there. Essentially, goto allows you to jump directly to a labeled statement elsewhere in your current method. You define a label (just a name followed by a colon) and tell the program to teleport there.


void DemoGoto()
{
    Console.WriteLine("Step 1");
    goto MyLabel; // Jump!
    Console.WriteLine("Step 2"); // This will never execute

MyLabel:
    Console.WriteLine("Step 3");
}

In the example above, "Step 2" is completely bypassed. It's straightforward, but that simplicity is exactly why it's dangerous.

Why is everyone so obsessed with avoiding it?

You'll hear the term "spaghetti code" a lot. When you start using goto to bounce around your logic—jumping from line 20 to 150, then back to 40—the flow of the program becomes a tangled mess. As a developer, you usually read code top-to-bottom. When goto is everywhere, you can't trust your eyes. You have to hunt through the file to find where the jump landed, and then try to remember the state of your variables at that exact moment.

I've spent hours debugging legacy systems where a single goto bypassed a critical variable initialization, causing a NullReferenceException that seemed to happen randomly. It's a nightmare. In 99% of cases, a while loop, a for loop, or just moving logic into a separate method is the cleaner, more professional way to handle the flow.

Are there any cases where I should actually use it?

Believe it or not, yes. There are a couple of niche scenarios where goto is actually the most concise tool for the job. The first is within a switch statement. C# doesn't allow implicit fall-through (like C++ does), but you can use goto case to explicitly jump to another case if they share logic.


switch (userRole)
{
    case "Admin":
        GrantAllPermissions();
        goto case "PowerUser"; // Share the PowerUser logic
    case "PowerUser":
        GrantAdvancedPermissions();
        break;
    case "Guest":
        GrantBasicPermissions();
        break;
}

The second scenario is breaking out of deeply nested loops. If you're three loops deep and find exactly what you're looking for, a standard break only gets you out of the innermost loop. You could use a bunch of boolean flags to signal the outer loops to stop, but a goto to a label outside the loops is occasionally cleaner and more performant.

Just remember: if you use it, leave a comment explaining why you chose it over a standard loop or method. Future you (and your teammates) will thank you.




📋 Practical Task

Refactoring the Nested Search Loop

You've inherited a piece of code that searches a 2D grid of coordinates for a "Target" value. The original developer used a goto statement to break out of the nested loops once the target was found. While it works, it feels a bit jarring.

Your Task: Take the following code and refactor it to remove the goto statement. Instead of jumping to a label, implement the solution by moving the search logic into its own method and using a return statement to exit the loops early.


public class GridSearcher
{
    public void FindTarget(int[,] grid, int target)
    {
        for (int i = 0; i < grid.GetLength(0); i++)
        {
            for (int j = 0; j < grid.GetLength(1); j++)
            {
                if (grid[i, j] == target)
                {
                    Console.WriteLine($"Found at {i},{j}");
                    goto EndSearch; 
                }
            }
        }

    EndSearch:
        Console.WriteLine("Search process complete.");
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.