Overblog Follow this blog
Edit post Administration Create my blog
Balavardhan Reddy Narani

GOTO statement in C#

May 20 2009 , Written by Balavardhan Reddy Published on #ASP.Net

GOTO
The goto statement transfers the program control directly to a labeled statement. It takes one of the following forms:


goto identifier;
goto case constant-expression;
goto default;


where:

identifier    A label.
constant-expression    A switch-case label.


Remarks

In the first form, the identifier indicates a label located in the current body, the same lexical scope, or an enclosing scope of the goto statement.

A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

The goto statement is also useful to get out of deeply nested loops.

A warning message may be issued if the label has never been referenced in the program. For more information on labels

Ex
For an example of using goto to transfer control to a specific switch-case label, see the switch example.

Ex
The following example demonstrates using goto to break out from nested loops.

using System;
public class Ex_GOTO
{
   public static void Main()
   {
      int x = 5, y = 1;
      int count = 0;
      string[,] myArray = new string[x,y];

      for (int i = 0; i < x; i++)
           for (int j = 0; j < y; j++)
                myArray[i,j] = (++count).ToString();      
   
     Console.Write("Enter the number to search for: ");

     string myNumber = Console.ReadLine();

     for (int i = 0; i < x; i++)
           for (int j = 0; j < y; j++)
                if (myArray[i,j].Equals(myNumber))
                      goto Found;

      Console.WriteLine("The number {0} was not found.", myNumber);
       goto Finish;


     Found:
             Console.WriteLine("The number {0} is found.", myNumber);

     Finish:
             Console.WriteLine("End of search.");
   }
}

Input
4


Sample Output
Enter the number to search for: 4
The number 4 is found.
End of search.

Share this post

Repost 0

Comment on this post

ONLINETV.CO.CC 07/03/2009 18:15

Check http://onlinetv.co.cc for lot of free TV channels like Sony,Zee,Star plus,HBO,Asianet,Surya,Sun TV etc