C# If....Else statements

if, else, and else if statements - also known as Conditional Statements are the foundation of decision-making in any programming language—and C# is no exception. If you want to write programs that react to user input, validate data, or control complex logic, mastering if, else, and else if statements is the perfect starting point

What Are Conditional Statements in C#?

Conditional statements allow your program to execute different blocks of code based on whether a condition is true or false.

They basically act like real-life decisions:
  • If it’s raining → take an umbrella
  • Else → go without umbrella
C# uses the following keywords to implement these conditions:
  • if
  • else
  • else if
Let’s understand each one clearly.

1. The if Statement in C#

The if statement runs a block of code only when the condition is true.

Syntax:

if (condition) {
  // code to execute if condition is true
}

Example:

int age = 20;

if (age >= 18)
{
    Console.WriteLine("You are eligible to vote.");
}
The condition age >= 18 evaluates to true, so the message is printed.

2. The else Statement in C#

The else block executes when the if condition is false.


if (condition)
{
    // true block
}
else
{
    // false block
}
Example:

int marks = 35;

if (marks >= 40)
{
    Console.WriteLine("You passed the exam!");
}
else
{
    Console.WriteLine("You failed the exam.");
}
Since 35 >= 40 is false, the program prints “You failed the exam”.

3. The else if Statement

Use else if when you need to test multiple conditions, one after another.

Syntax:

if (condition1)
{
    // executes if condition1 is true
}
else if (condition2)
{
    // executes if condition2 is true
}
else
{
    // executes if none are true
}
Example: Grading System

int score = 72;

if (score >= 90)
{
    Console.WriteLine("Grade A");
}
else if (score >= 75)
{
    Console.WriteLine("Grade B");
}
else if (score >= 60)
{
    Console.WriteLine("Grade C");
}
else
{
    Console.WriteLine("Grade D");
}

When Should You Use If, Else, and Else If?

Keyword When to Use
if When you need to check a condition.
else When the previous if condition is false and you want an alternative action.
else if When you have multiple possible outcomes.

Summary

In C#, conditional statements like if, else and else if help your program choose what action to take based on different situations. The if statement checks the main condition, else handles the opposite case, and else if allows additional checks when more outcomes are possible. These structures form the backbone of decision-making in C# applications. Mastering them enables you to write smarter, more flexible, and user-responsive code.