C# Goto Statement – Understanding Goto in C# with Examples

The goto in C# is a jump statement that transfers the control to another part of the program. This comprehensive guide includes code examples, advantages, and disadvantages of using the goto statement, to help you make an informed decision.

goto statement in csharp
C# goto statement

C# Goto Definition:

The goto statement in C# is a jump statement that allows the programmer to transfer control to a specific label within the program.

We can use the goto statement in many different scenarios in C# programming, including:

  • Breaking out of nested loops
  • Jumping to error handling code
  • Creating infinite loops
  • Controlling the flow of complex logic

Example 1: Breaking out of nested loops using goto in C#:

In C#, We can use the goto statement to break out of nested loops. It can be especially useful when multiple nested loops are used, and the programmer wants to exit them simultaneously.

using System;
using System.IO;
namespace GotoExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // loop through values of i from 0 to 4
            for (int i = 0; i < 5; i++)
            {
                // nested loop through values of j from 0 to 4
                for (int j = 0; j < 5; j++)
                {
                    // output the values of i and j
                    Console.WriteLine("i: {0}, j: {1}", i, j);
                    // if j is equal to 2, jump to the label "end"
                    if (j == 2)
                    {
                        goto end;
                    }
                }
            }
            end:
            Console.WriteLine("Outside loops");
            Console.ReadLine();
        }
    }
}

Output:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
Outside loops

Example 2: Jumping to error handling code:

In C#, the goto statement can redirect the program flow to the error handling code in case an error occurs. It could be helpful in that scenarios where the error handling code is not located near the source of the error, and the programmer intends to make it easily accessible.

using System;
using System.IO;
namespace SystemIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int x = int.Parse("abc");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                goto end;
            }
            end:
            Console.WriteLine("Outside try-catch block");
            Console.ReadLine();
        }
    }
}
go to in c# example

Example 3: Creating infinite loops using goto in C#:

The goto in C# can be used to create infinite loops. It can be beneficial when the programmer wants to run a loop continuously until a specific condition is met.

 // Start label to repeat the process if the number entered is not greater than 10
            start:

            // Prompt user to enter a number greater than 10
            Console.WriteLine("Enter a number greater than 10:");

            // Read the user input and store it in the "number" variable
            int number = int.Parse(Console.ReadLine());

            // Check if the number entered is less than or equal to 10
            if (number <= 10)
            {
                // If the number is not greater than 10, go back to the start label
                goto start;
            }
            else
            {
                // If the number is greater than 10, print a message
                Console.WriteLine("Number is greater than 10");
            }
            Console.ReadLine();

Output:

goto in csharp example

Example 4: Using switch statement with goto in C#: 

We can also combine the goto statement with the switch statement in C#. This example demonstrates how we can implement a label within the switch statement to jump to a specific case.

Let’s take an example of a program that calculates the day of the week based on the number entered by the user.

using System;

namespace GotoExample4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number between 1 to 7:");
            int day = Convert.ToInt32(Console.ReadLine());
            switch (day)
            {
                case 1:
                    Console.WriteLine("Monday");
                    break;
                case 2:
                    Console.WriteLine("Tuesday");
                    break;
                case 3:
                    Console.WriteLine("Wednesday");
                    break;
                case 4:
                    Console.WriteLine("Thursday");
                    break;
                case 5:
                    Console.WriteLine("Friday");
                    break;
                case 6:
                    Console.WriteLine("Saturday");
                    break;
                case 7:
                    Console.WriteLine("Sunday");
                    break;
                default:
                    Console.WriteLine("Invalid Input");
                    goto end;
            }
            Console.WriteLine("Thank you for using the program.");
            end:
            Console.WriteLine("Exiting the program.");
            Console.ReadLine();
        }
    }
}

Output:

Enter a number between 1 to 7:
5
Friday
Thank you for using the program.
Exiting the program.

Pros and Cons of the C# Goto Statement: 

The goto statement in C# has pros and cons, and it is up to the programmer to decide whether to use it.

Pros:

  • Easy to understand and implement
  • Can simplify complex logic
  • Can save time by reducing the need for multiple conditional statements

Cons:

  • It can make the code difficult to maintain and debug
  • It can lead to unexpected results if not used correctly
  • It can make the code less readable and more challenging to understand

FAQs

Q: What is the goto in C#?

The goto statement in C# is a control statement that allows a programmer to transfer the flow of execution to another statement in the same function.

Q: How does the goto statement work in C#?

The goto statement transfers the flow of execution to a labeled statement in the same function. The programmer defines the label, and it is used as a destination for the goto statement.

Q: What are the advantages of using the goto statement in C#?

The advantages of using the goto statement in C# include its simplicity, ability to simplify complex logic, and ability to save time by reducing the need for multiple conditional statements.

Q: What are the disadvantages of using the goto in C#?

The disadvantages of using the goto statement in C# include its potential to make the code more difficult to maintain and debug. It will lead to unexpected results if used correctly and make the code less readable and easier to understand.

Q: Can the goto statement be combined with other control statements in C#?

Yes, we can use the goto statement in combination with other control statements, such as the switch statement in C#.

Q: What is an example of using the goto statement in C#?

An example of using the goto in C# is to jump to the error handling code when an error occurs in the program, making the error handling code easily accessible. Another example is implementing a label within a switch statement to jump to a specific case.

References: MSDN-Jump-Statements

Articles you might also like:

Please share this post and let us know what you think in the comments.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments