MenuHeader

Wednesday 28 February 2024

Branching Statements- in C# || Full C# course || ABFirstTech

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:

  1. 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); }


  2. 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); }


  3. 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; }


  4. 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; }


  5. 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; }


  6. While break and continue are often used in loops, return and throw are used in methods/functions to control the program's flow. The use of goto should be avoided in most cases due to its negative impact on code readability and maintainability.

No comments:

Post a Comment

Angular Interview Questions and Answers 2024 (Real interview) | Angular 18

real time angular interview questions and answers realtime angular interview questions and answers, Top Angular Interview Questions, angular...