In C#, the Goto statement, also recognized as a jump statement, is utilized to redirect program flow to a different section. This command unconditionally moves execution to the designated label. It is handy for transitioning control out of a highly nested switch case label or loop structure.
Syntax:
It has the following syntax:
goto label;
. . .
label:
// Code to be executed after the jump
In C#, the goto keyword is used to transfer control to a labeled statement within the same method. It is commonly used to navigate to a specific point in the code.
Flowchart of the Goto Statement:
The CSS code below defines the styling for a diagram component:
.goto-diagram {
background: linear-gradient(135deg, #2e1a2e 0%, #1f1f2d 100%);
border-radius: 12px;
padding: 25px;
margin: 20px 0;
}
.goto-diagram .diagram-title {
text-align: center;
color: #f472b6;
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 20px;
}
.goto-diagram .goto-flow {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.goto-diagram .flow-node {
padding: 10px 20px;
border-radius: 8px;
text-align: center;
font-weight: 500;
color: white;
}
.goto-diagram .flow-node.start,
.goto-diagram .flow-node.end {
background: #4ade80;
color: #0d1b2a;
border-radius: 20px;
}
.goto-diagram .flow-node.process {
background: #3b82f6;
}
.goto-diagram .flow-node.goto-node {
background: #f472b6;
color: #0d1b2a;
font-weight: 700;
}
.goto-diagram .flow-node.label-node {
background: #8b5cf6;
border: 2px dashed #c084fc;
}
.goto-diagram .flow-arrow {
color: #64748b;
font-size: 1.3rem;
}
.goto-diagram .flow-arrow.jump {
color: #f472b6;
font-weight: 600;
}
In the flowchart provided, follow these steps to incorporate the C# Goto Statement:
Step 1: The program starts from the Start block.
Step 2: It executes the first Statement.
Step 3: Next, it evaluates a condition to decide whether to proceed to Label 2 using a goto statement.
When the goto function is invoked, the program's control jumps directly to Label 2, bypassing Statement 1.
In the alternate scenario, it proceeds in sequence to Statement 1 followed by Statement 2.
Step 6: After Statement 2 is executed, the path progresses to the End point.
C# Goto Statement Example
Let's explore a straightforward example showcasing the use of the goto statement in C#.
Example
using System;
public class GotoExample
{
public static void Main(string[] args)
{
ineligible:
Console.WriteLine("You are not eligible to vote!");
Console.WriteLine("Enter your age:\n");
int age = Convert.ToInt32(Console.ReadLine());
if (age < 18){
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to vote!");
}
}
}
Output:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!
C# Goto Statement with for Loop
In C#, the goto statement transfers control to a labeled statement within the same method. While generally discouraged due to its impact on code readability, it can be employed to exit nested loops or skip over code segments under certain conditions.
Syntax:
It has the following syntax:
for (initialization; condition; updatation)
{
if (expression)
{
goto label; // Jump to the labeled statement
}
// Code to be executed if 'goto' is not hit
}
label:
// Code to be executed after the jump
C# Goto Statement Example using for Loop:
Let's consider an example to demonstrate the application of the Goto statement within a for loop in C#.
Example
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 6)
{
goto End;
}
Console.WriteLine(i);
}
End:
Console.WriteLine("Loop terminated at 6.");
}
}
Output:
1
2
3
4
5
Loop Terminated at 6
Explanation:
In this instance, the for loop cycles through values ranging from 1 to 10. Upon reaching the value of 6 for i, the goto End; statement is executed, redirecting the flow to the End: label. Consequently, the loop is prematurely halted, triggering the display of the message "Loop terminated at 6."
C# Goto statement with Switch Statement
In C#, the goto keyword is applicable within a switch statement to navigate to a specific case label or the default label. This feature proves useful when there is a requirement to shift control from one case to another.
Syntax
It has the following syntax:
switch (expression)
{
case value1:
// Code for case 1
goto case value2; // Jump to another case
case value2:
// Code for case 2
break;
default:
// Default case code
break;
}
C# Goto Statement Example using Switch Statement
Let's consider a scenario to demonstrate the use of the goto statement alongside the switch statement in C#.
Example
using System;
class Program
{
static void Main()
{
int day = 3;
Console.WriteLine("Day number: " + day);
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
goto case 5;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Console.WriteLine("End of the program.");
}
}
Output:
Day number: 3
Wednesday
Friday
End of the program.
Explanation
In this instance, the switch statement evaluates the day's value, which is 3. Control flows to case 3 and displays "Wednesday". Following that, the program jumps to case 5 using the goto statement.
Following that, the program outputs "Friday", and then exits the switch statement. Subsequently, the program concludes by displaying "End of the program.".
C# Goto with Nested Loops
In C#, the goto keyword can be employed within nested loops to terminate multiple loops simultaneously or to jump to a labeled statement. It is useful when there is a need to exit all loops collectively based on a particular condition.
Syntax
It has the following syntax:
for (initialization; condition; update)
{
for (initialization; condition; update)
{
if (expression)
{
goto label; // Jump to the labeled statement
}
// Inner loop code
}
// Outer loop code
}
label:
// Code to be executed after the jump
C# Goto Statement Example using Nested Loop
Let's consider a scenario to demonstrate the Goto Statement within a nested loop in C#.
Example
using System;
class Program
{
static void Main()
{
Console.WriteLine("Checking students marks to find the target:");
string[] students = { "Alice", "Bob", "Charlie", "David", "Eva" };
int[] marks = { 85, 90, 78, 92, 88 };
foreach (string i in students)
{
foreach (int j in marks)
{
Console.WriteLine($"Checking marks of {i}: {j}");
if (i == "Bob" && j == 90)
{
Console.WriteLine("Target student found: Bob with 90 marks!");
goto End;
}
}
}
End:
Console.WriteLine("Process completed.");
}
}
Output:
Checking students marks to find the target:
Checking marks of Alice: 85
Checking marks of Alice: 90
Checking marks of Alice: 78
Checking marks of Alice: 92
Checking marks of Alice: 88
Checking marks of Bob: 85
Checking marks of Bob: 90
Target student found: Bob with 90 marks!
Process completed.
Explanation
In this instance, we loop through a roster of pupils and mark them off using nested forEach loops. Subsequently, it examines each possible pairing to locate the student named "Bob" who achieved a score of 90.
Once identified, a notification appears confirming the discovery of the target and employs the goto command to exit both loops at the same time. Ultimately, it presents the message "Process completed." to indicate the successful completion of the execution.
Conclusion
In summary, the goto statement in C# offers a way to transfer control directly to a labeled statement within the same function. Although it can be beneficial in certain scenarios like escaping from complex nested loops or when designing finite state machines, it is generally discouraged due to its negative impact on code readability and maintainability.
C# Goto Statement MCQs
- What is the primary purpose of the goto statement in C#?
- To create new variables
- To execute code conditionally
- To transfer control to a labeled statement
- To define a method
- What is the use of goto generally discouraged in C#?
- It causes compile-time errors
- It can make code harder to read and maintain
- It slows down the program significantly
- It is not supported in modern C# versions
- In the example with nested loops, what does goto End; do?
- Breaks both loops and jumps to the labeled statement
- Skips only the inner loop
- Breaks only the outer loop
- Restarts both loops from the beginning
- Which of the following is a valid use of the goto statement?
- Jumping to a label in another class
- Jumping backward and forward to any method
- Automatically repeating loops
- Jumping to a labeled statement within the same method
- What happens when a goto statement is used to jump to a label within the same method?
- The program exits immediately
- The program crashes
- The control jumps unconditionally to that label
- The method is re-executed from the beginning
The program control unconditionally transfers to the specified label.