BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Goto Statement

The thirty-third part of the C# Fundamentals tutorial reviews the use of the jump statement, 'goto'. This command is rarely used and often scorned but does provide a valuable function when used with the switch statement to control program flow.

Spaghetti Code

The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to spaghetti code. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems.

Basic Syntax

The basic syntax of the goto statement is very simple. Firstly a label must be created at within the code. This becomes the destination for the jump. A label is defined by providing a name followed by a colon (:). The goto statement references the label as shown below:

Console.WriteLine("This will get outputted.");

goto myLabel;

Console.WriteLine("This will not get outputted.");

myLabel:

Console.WriteLine("This will get outputted too.");

It should be noted that the destination label must be in the same method as the goto that calls it. In some cases, the label must be within the same code block.

Goto and Switch

When using switch for conditional processing, each case statement also defines a label. The goto command may be used to jump between cases, allowing a cascading chain of case statements to be executed rather than a single item. A break statement is not required in a case that ends with a goto.

The following example shows a switch statement used to interpret a status code. In the example, the "Warn" case is executed first, followed by the "Complete" case. This example also shows how quickly code can become difficult to read if the goto command is used carelessly.

string statusCode = "Warn";

switch (statusCode)
{
    case "Warn":
        Console.WriteLine("Completed with warnings.");
        goto case "Complete";
    case "Err":
        Console.WriteLine("Completed with errors.");
        goto case "Complete";
    case "Complete":
        Console.WriteLine("Completed.");
        break;
    case "Fail":
        Console.WriteLine("Failed to complete.");
        break;
    default:
        Console.WriteLine("Unknown status code");
        goto case "Fail";

NB: The goto command may only be used to jump between cases including the default case. Jumps into or out of the entire switch statement are not permitted.

13 March 2007