Course Content
C# Tutorial
About Lesson

Conditional statements (if-else, switch)

Conditional statements in C# are essential constructs that control the flow of a program based on certain conditions. They allow developers to create logic that executes code blocks selectively, enhancing the flexibility and control within their applications.

The “if-else” Statement

The “if-else” statement is fundamental in C#. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, an alternative block of code can be executed. Here’s an example:

int number = 10;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is not positive.");
}

The “switch” Statement

The “switch” statement provides an efficient way to handle multiple conditions based on the value of an expression. It allows the execution of different code blocks depending on various possible values of the expression. Consider this example:

char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good job!");
break;
case 'C':
Console.WriteLine("Fair, but keep improving.");
break;
default:
Console.WriteLine("Work harder!");
break;
}

Comparison Between “if-else” and “switch”

While both serve similar purposes, choosing between “if-else” and “switch” depends on the specific scenario. “if-else” is more suitable when dealing with complex conditions or ranges, whereas “switch” is ideal for cases where there’s a need to evaluate the value of a single variable against multiple values.

Best Practices for Using Conditional Statements

  1. Clarity and Readability: Ensure your code is easy to understand by using meaningful variable names and well-structured conditions.
  2. Avoid Nested Statements: Excessive nesting can make code hard to follow. Consider refactoring nested “if-else” statements for improved readability.
  3. Use “switch” for Multiple Comparisons: When dealing with multiple conditions for a single variable, “switch” can offer a more concise and organized solution.
  4. Handling Default Cases: Always include a default case in “switch” statements to manage unexpected scenarios