C# Jump Statements(Break, Continue, Goto, Return and Throw)

Jump Statements(Break, Continue, Goto, Return and Throw)

Jump statements in C# are used to transfer control from one part of a program to another. In this tutorial, we will cover the jump statements break, continue, goto, return, and throw.

1. Break:

The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement.

Example:

for (int i = 0; i < 10; i++) { if (i == 5) { break; // Breaks out of the loop when i equals 5. } Console.WriteLine(i); } 

2. Continue:

The continue statement skips the remaining statements in the current iteration of a loop and moves to the next iteration.

Example:

for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // Skips even numbers. } Console.WriteLine(i); } 

3. Goto:

The goto statement transfers control to a labeled statement in the same function.

Example:

for (int i = 0; i < 10; i++) { if (i == 5) { goto End; // Jumps to the 'End' label. } Console.WriteLine(i); } End: Console.WriteLine("End of loop."); 

Note: Overuse of goto is discouraged, as it can make code harder to read and maintain.

4. Return:

The return statement terminates the execution of the method and optionally returns a value from that method.

Example:

public int Add(int a, int b) { return a + b; // Returns the sum of a and b. } 

5. Throw:

The throw statement is used to signal the occurrence of an exception during program execution.

Example:

public void CheckAge(int age) { if (age < 0) { throw new ArgumentException("Age cannot be negative."); } } 

When to Use Each Statement:

  1. Break: Used to prematurely exit a loop or switch case.
  2. Continue: To skip a particular iteration in a loop.
  3. Goto: Transfer control to a specific label, though its use is discouraged in favor of more structured flow control.
  4. Return: Exit a method and optionally provide a value back to the caller.
  5. Throw: Indicate that an exceptional situation has occurred.

Conclusion:

Jump statements play a crucial role in controlling the flow of a C# program. Understanding when and how to use each will make your code more effective and easier to understand.


More Tags

tvos httponly registry ado time-series generics rest-client class wear-os runtime.exec

More Programming Guides

Other Guides

More Programming Examples