-
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
- if
- else
- else if
1. The if Statement in C#
The if statement runs a block of code only when the condition is true.
Syntax:
Example:if (condition) { // code to execute if condition is true }
The conditionint age = 20; if (age >= 18) { Console.WriteLine("You are eligible to vote."); }age >= 18evaluates to true, so the message is printed.
2. The else Statement in C#
The else block executes when the
ifcondition is false.
Example:if (condition) { // true block } else { // false block }
Sinceint marks = 35; if (marks >= 40) { Console.WriteLine("You passed the exam!"); } else { Console.WriteLine("You failed the exam."); }35 >= 40is false, the program prints “You failed the exam”.
3. The else if Statement
Use
Syntax:else ifwhen you need to test multiple conditions, one after another.
Example: Grading Systemif (condition1) { // executes if condition1 is true } else if (condition2) { // executes if condition2 is true } else { // executes if none are true }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 ifcondition 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.