There are four main jump statements in C#. Jump statements tell execution to jump to a specific point rather than necessarily being associated with a code block.
The break statement dictates that the execution should leave the current code block. We saw this earlier in the case of a switch statement where it did not make sense to evaluate the other cases so instead, we broke out of the switch statement.
using System;
public class Program
{
public static void Main()
{
int i = 4;
addOneToi:
if(i<9)
{
i++;
Console.WriteLine(i);
goto addOneToi;
}
Console.WriteLine("End of execution");
}
}
The continue statement is specific to loops. When a continue statement is encountered, the remaining statements in the loop are not executed and the loop will proceed to the next iteration.
using System;
public class Program
{
public static void Main()
{
for(var i = 1; i < 20; i++)
{
if(i%2==0)
continue;
else
Console.WriteLine(i.ToString());
}
}
}
The goto statement will move execution to a specified label or switch case.
A label is an identifier that is followed by a semicolon and specifies a significant point in the code.
using System;
public class Program
{
public static void Main()
{
int i = 4;
addOneToi:
if(i<9)
{
i++;
Console.WriteLine(i);
goto addOneToi;
}
Console.WriteLine("End of execution");
}
}
The return statement ends the method and will return a value to where it was called from. The return keyword is only valid if the statement is not void.
using System;
public class Program
{
public static int return1()
{
return 1;
}
}
A return statement does not have to be at the end of a method, it could exist within a select statement. However, a return statement must always eventually be hit for a non-void method.
Throw statements generally suggest that an error has occurred within the application. We will visit this topic in more depth in a later tutorial when we discuss errors and the measures we can take to mitigate their impact.
The using statement is used when you only want an object to exist for a small, set number of statements, after which point the object will be disposed of.
using System;
public class Program
{
public static void Main()
{
//using(exampleClass s = new exampleClass())
//{
// s.methodExample(s);
//}
}
}