Friday, 17 August 2018

C#: goto statement

By using goto statement, we can transfer the control to a label. Label is a marker in the program, where your code can jump there directly.

Syntax
goto label;

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a Number");

        int num = int.Parse(Console.ReadLine());

        if(num == 5)
        {
            goto error;
        }else
        {
            Console.WriteLine("You Entered {0}", num);
            goto exit;
        }

        error:
        Console.WriteLine("Wrong Choice");
        System.Environment.Exit(1);

        exit:
        Console.WriteLine("Exiting Successfully");
        System.Environment.Exit(0);
    }
}

Sample Output1
Enter a Number
5
Wrong Choice

Sample Output2
Enter a Number
10
You Entered 10
Exiting Successfully




Previous                                                 Next                                                 Home

No comments:

Post a Comment