Branching Statements- in C#
Branching statements in C# are used to alter the normal flow of program execution. They include keywords like break
, continue
, return
, goto
, and throw
. Let's discuss each of these branching statements:
break
statement:Used to exit from a loop or switch statement prematurely.
Example:
for (int i = 0; i < 10; i++) { if (i == 5) { break; // exit the loop when i equals 5 } Console.WriteLine(i); }
continue
statement:Used to skip the rest of the loop and jump to the next iteration.
Example:
for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // skip even numbers } Console.WriteLine(i); }
return
statement:Used to exit a method and return a value, if the method has a return type.
Example:
int Square(int x) { return x * x; }
goto
statement:Allows you to transfer the control of the program to a labeled statement.
It is generally considered bad practice and is rarely used in modern C# programming due to its potential to create unreadable and hard-to-maintain code. It can lead to "goto spaghetti" code.
Example:
int i = 0; loopStart: Console.WriteLine(i); i++; if (i < 5) { goto loopStart; }
throw
statement:Used to raise an exception explicitly.
Example:
int Divide(int numerator, int denominator) { if (denominator == 0) { throw new DivideByZeroException("Denominator cannot be zero."); } return numerator / denominator; }
- While
break
andcontinue
are often used in loops,return
andthrow
are used in methods/functions to control the program's flow. The use ofgoto
should be avoided in most cases due to its negative impact on code readability and maintainability.
No comments:
Post a Comment