C# goto Keyword

C# Code Snippets goto Keyword
Share:

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 loopsif 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();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger