C# if else Statement


The if-else statement in C# allows you to execute different blocks of code based on whether a condition evaluates to true or false. It enables decision-making, allowing the program to choose a course of action based on the condition provided.

1. Syntax of the if-else Statement

The syntax of an if-else statement in C# is as follows:

if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
  • condition: A boolean expression that is evaluated. If it is true, the code inside the if block is executed. If it is false, the code inside the else block is executed.

2. Example of an if-else Statement

int number = 8; if (number > 10) { Console.WriteLine("The number is greater than 10."); } else { Console.WriteLine("The number is less than or equal to 10."); }

Explanation:

  • In this example, the if statement checks whether the value of number is greater than 10.
  • Since 8 is not greater than 10, the condition evaluates to false, so the else block is executed, and "The number is less than or equal to 10." is printed.

3. Flow of Execution

  1. The condition in the if statement is evaluated.
  2. If the condition is true, the code inside the if block is executed, and the else block is skipped.
  3. If the condition is false, the code inside the else block is executed.

4. Example with User Input

Console.Write("Enter a number: "); int number = Convert.ToInt32(Console.ReadLine()); if (number % 2 == 0) { Console.WriteLine("The number is even."); } else { Console.WriteLine("The number is odd."); }

Explanation:

  • The user inputs a number, which is checked to see if it is even (using number % 2 == 0).
  • If the condition is true (i.e., the number is divisible by 2), the if block runs and prints "The number is even.".
  • If the condition is false, the else block runs and prints "The number is odd.".

5. Example with a More Complex Condition

int age = 18; if (age >= 18) { Console.WriteLine("You are eligible to vote."); } else { Console.WriteLine("You are not eligible to vote."); }

Explanation:

  • The condition age >= 18 checks whether the person is 18 years old or older.
  • If the condition is true (age is 18 or more), the program prints "You are eligible to vote.".
  • If the condition is false (age is less than 18), the program prints "You are not eligible to vote.".