There are several jump statements available in C#, those are a break, continue, goto, return, and throw. In this article, we discuss each of these jump statements with an example.
Break statement: The break statement used to end the switch statement execution or execution of the body of an iteration as shown below.
class Program
{
static void Main(string[] args)
{
int value = 1;
switch (value)
{
case 1:
Console.WriteLine("Value is One");
break;
default:
Console.WriteLine("No Value");
break;
}
for (int n = 0; n < 50; n++)
{
if (n == 10)
{
break;
}
DoThings();
}
}
private static void DoThings()
{
}
}
Continue statement: We can use continue statement inside a for loop statement. The continue statement forgoes the remaining statements inside for loop and makes an early call to next iteration like below.
class Program
{
static void Main(string[] args)
{
for (int n = 0; n < 50; n++)
{
if (n == 10)
{
continue;
}
DoThings();
}
}
private static void DoThings()
{
}
}
Goto statement: The go tot statement is used to transfer the execution to a specific label in C#. In C#, the label is a placeholder in a code block that precedes a statement and specified with a colon as a suffix.
class Program
{
static void Main(string[] args)
{
int n = 100;
if(n>90)
{
goto Found;
}
Found:
Console.WriteLine("The number {0} is found.", n);
Console.ReadLine();
}
}
Return statement: The return statement exits from the true method and returns a specific type of data for non-void methods as shown below.
class Program
{
static void Main(string[] args)
{
string sValue = DoThings();
}
private static string DoThings()
{
return "return value";
}
}
We can place return statement anywhere in a method others than in a finally block. We cannot mention return statement in the finally block.
Throw statement: By using throw statement, we can throw an exception to indicate an error has occurred.
class Program
{
static void Main(string[] args)
{
DoThings();
}
private static void DoThings()
{
Exception ex = new Exception();
throw ex;
}
}