Control flow refers to the order in which statements are executed in a program. In C#, there are several control flow structures that allow you to control the execution of code based on conditions or loops.
1. Conditional Statements:
– `if` statement: Executes a block of code if a condition is true.
– `else` statement: Executes a block of code if the `if` condition is false.
– `else if` statement: Allows for multiple conditions to be checked in sequence.
– `switch` statement: Executes different blocks of code based on the value of an expression.
2. Looping Statements:
– `while` loop: Repeatedly executes a block of code as long as a condition is true.
– `do-while` loop: Executes a block of code once, and then repeatedly executes it as long as a condition is true.
– `for` loop: Executes a block of code a specified number of times, based on an initialization, condition, and increment.
– `foreach` loop: Iterates over a collection of elements, such as an array or a list.
– `break` statement: Terminates the execution of a loop.
– `continue` statement: Skips the remaining code in a loop and continues with the next iteration.
3. Jump Statements:
– `goto` statement: Transfers the control to a labeled statement.
– `return` statement: Exits a method and returns a value to the caller.
– `throw` statement: Throws an exception to indicate an error condition.
4. Exception Handling:
– `try-catch` statement: Catches and handles exceptions that occur during the execution of a block of code.
– `finally` statement: Specifies a block of code that is always executed, regardless of whether an exception is thrown or caught.
These control flow structures allow for the execution of code to be controlled based on conditions or to be repeated for a certain number of times.