Control Flow and Decision Making in C#

January 2, 2024

This post delves into the concept of control flow and decision making in C#. It covers conditional statements, loops, and other control structures that allow for more complex and dynamic code.

Conditional Statements

In C#, conditional statements are used to perform different actions based on different conditions. The if statement is the most basic form of a conditional statement. It allows you to execute a block of code if a specified condition is true.

if (condition)
{
    // code to be executed if the condition is true
}

Additionally, you can use the else statement to specify a block of code to be executed if the condition is false:

if (condition)
{
    // code to be executed if the condition is true
}
else
{
    // code to be executed if the condition is false
}

Furthermore, C# provides the else if statement for handling multiple conditions:

if (condition1)
{
    // code to be executed if condition1 is true
}
else if (condition2)
{
    // code to be executed if condition2 is true
}
else
{
    // code to be executed if all conditions are false
}

Loops

Loops in C# are used to execute a block of code repeatedly. The while loop executes a block of code as long as a specified condition is true:

while (condition)
{
    // code to be executed while the condition is true
}

The do while loop is similar to the while loop, but it ensures that the block of code is executed at least once before the condition is checked:

do
{
    // code to be executed
} while (condition);

Another type of loop is the for loop, which allows you to execute a block of code a specific number of times:

for (int i = 0; i < 10; i++)
{
    // code to be executed
}

There’s also the foreach loop, which is used to iterate through elements in an array or collection:

foreach (var item in collection)
{
    // code to be executed for each item in the collection
}

Switch Statement

The switch statement is used to select one of many code blocks to be executed. It evaluates an expression and matches the value of the expression to a case label:

switch (expression)
{
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    default:
        // code to be executed if expression doesn't match any case
        break;
}