Jump Statements in C#

Jump Statements in C#

 

In this article, you will learn about C# jump statements, these statements help in transferring control from one point to the other. Positioning the execution based on a certain requirement is another concept that helps in jumping from a particular logic to others within a program.

 

Jump Statements in C#
 
goto
 
using System;
namespace ConsoleApplication
{
class usingcsharp
{ 
    static void Main(string[] args)
    {
        Console.WriteLine(" Goto Start ");
        goto g;
        Console.WriteLine(" This line gets skipped ");
        g:
        {
            Console.WriteLine(" This section will be displayed ");
        }            
        Console.Read();
    }
}
}

 

break

 

for (int i = 0; i < 20; i++) 
{
  if (i == 10) 
  {
    break;
  }
  Console.WriteLine(i);
}
 

int i = 0;
while (i < 20) 
{
  if (i == 10) 
  {
    i++;
    continue;
  }
  Console.WriteLine(i);
  i++;
}

 

continue

 

int i = 0;
while (i < 20) 
{
  if (i == 10) 
  {
    i++;
    continue;
  }
  Console.WriteLine(i);
  i++;
}

 

for (int i = 0; i < 20; i++) 
{
  if (i == 10) 
  {
    break;
  }
  Console.WriteLine(i);
}

 

return

 

using System; 
class usingcsharp
{ 
static int Add(int a) 
{
    int b = a + a; 
    return b; 
} 
static public void Main() 
{ 
    int num = 10; 
    int result = Add(num); 
    Console.WriteLine(" Addition is: {0} : ", result); 
} 
}

 

throw

 

using System; 
class usingcsharp
 { 
    static string b = null;  
    static void displaymsg(string a) 
    { 
        if (a  == null) 
            throw new NullReferenceException("Exception Found.");              
    }    
static void Main(string[] args) 
{  
    try
    { 
        displaymsg(b); 
    }  
    catch(Exception ex) 
    { 
        Console.WriteLine( ex.Message ); 
    }                      
} 
}

2021-10-03