How goto statement works in this example?

Mircea picture Mircea · Aug 31, 2010 · Viewed 39.5k times · Source

I am studying this code sample:

class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = 10;

        int generate=0;

        string [,] myArrayTable = new string[x, y];

        Console.WriteLine("Enter a seek number: ");
        string cautat = Console.ReadLine();

        for (int i = 0; i < x; i++)
        {
            for(int j = 0;j < y; j++)
            {
                myArrayTable[i, j] = (generate++).ToString();
            }
        }

        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(cautat.Equals(myArrayTable[i,j]))
                {
                    goto Found; 
                }
            }
        }

        goto NotFound;

        Found: 
          Console.WriteLine("Numarul a fost gasit");

        NotFound:
         Console.WriteLine("Numarul nu a fost gasit !");

        Console.ReadKey();
    }
}

I do not understand why the "Not Found" statement was called and its corresponding message print on console if i enter a seek number like 10, in this case goto: Found statement is executing, so goto: NotFound statement will never be called, but still its corresponding message is printed on console, i do not understand how since in this case program never jumps to this "NotFound" label.

Please if you now give me a hand about this...

Thanks

Answer

SwDevMan81 picture SwDevMan81 · Aug 31, 2010

Eww goto's, I would use and if/else statement, but if you need goto's:

Found: 
  Console.WriteLine("Numarul a fost gasit");
  goto End;
NotFound:
  Console.WriteLine("Numarul nu a fost gasit !");
End:
Console.ReadKey();