About
In thisĀ code snippet, we will take a look at the goto keyword in C#.
goto is used to move the control of your program to a label you define beforehand. This can be useful to get out of nestedĀ loops,Ā if statementsĀ or any nested code blocks in general.
You can even make a DIY loop orĀ methodĀ using the goto keyword š(But you should of course use the regular loops and methods).
Letās have a look at the code below to see how to use goto.
Code:
using System;
namespace gotoStatement
{
class Program
{
static void Main(string[] args)
{
//The goto keyword can be used to redirect the flow of your program to a marked point.
//You can make a mark/tag by just writing some text and ending it with a :
//Then you can point at it using goto.
//See examples bellow:
#region Break out of loop using goto
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (i == 5 && j == 2)
goto breakOutOfLoop;
}
}
breakOutOfLoop: Console.WriteLine("Loop was ended.");
#endregion
#region DIY loop using goto.
int k = 0; //Declare and initilize counter.
loopBegin: //Mark beginning point.
Console.WriteLine(k);//Execute code inside loop.
k++; //Increment loop counter.
if (k < 5) //Check if counter is smaller than 5. If so ...
goto loopBegin; //Go to the beginning.
#endregion
Console.ReadLine();
}
}
}





