Menu
Coddy logo textTech

Jump Statements (goto)

Part of the Logic & Flow section of Coddy's C# journey — lesson 20 of 66.

The goto statement in C# provides a way to transfer control directly to a labeled statement within the same method.

Create a label in your code:

start:

Use the goto statement to jump to that label:

goto start;

Here's a simple example that uses goto to create a loop:

int i = 0;

start:
if (i < 5)
{
    Console.WriteLine(i);
    i++;
    goto start;
}

After executing the above code, the output will be:

0
1
2
3
4

While goto exists in C#, it's generally recommended to use structured control flow statements (if, for, while, etc.) instead, as they make code more readable and maintainable.

challenge icon

Challenge

Easy

Create a method named ProcessCommands that takes one argument:

  • A string (command) that contains a command to process.

The method should implement a simple command processor using goto statements:

  • If the command is "start", print "Starting process" and then go to the "end" label
  • If the command is "stop", print "Stopping process" and then go to the "end" label
  • If the command is "pause", print "Pausing process" and then go to the "end" label
  • If the command is anything else, print "Unknown command" and then go to the "end" label
  • At the "end" label, print “Command processed”

Cheat sheet

The goto statement transfers control directly to a labeled statement within the same method.

Create a label:

start:

Jump to a label using goto:

goto start;

Example using goto to create a loop:

int i = 0;

start:
if (i < 5)
{
    Console.WriteLine(i);
    i++;
    goto start;
}

While goto exists in C#, structured control flow statements (if, for, while, etc.) are generally recommended for better code readability and maintainability.

Try it yourself

using System;

public class Program
{
    public static void ProcessCommands(string command)
    {
        // Write your code here
    }
    
    public static void Main(string[] args)
    {
        string command = Console.ReadLine();
        ProcessCommands(command);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow