Conditional Statements in C# – If, Else, Switch and Ternary Operator
Quick Answer: Conditional statements help a C# program make decisions. They run different code based on conditions. Use if and else for decisions, switch for multiple fixed choices, and the ternary operator for short two-way results.
1. Why Do We Need Conditional Statements?
Imagine you manage a school with 1,000 students. Every student has marks, attendance and an admission status.
How will your application decide who passes an exam? How will it assign grades? How will it show different student services?
Think about these decisions before reading the code.
A program without conditions can only follow fixed instructions. It cannot choose a different result for different students.
The Problem: Fixed Instructions Without Conditions
Consider three students with different exam marks. We want to display their results.
The following program prints fixed messages. It does not check the marks.
Example 1: Printing fixed student results
using System;
int raviMarks = 82;
int priyaMarks = 35;
int arjunMarks = 58;
Console.WriteLine("Ravi: Pass");
Console.WriteLine("Priya: Fail");
Console.WriteLine("Arjun: Pass");
Expected output
Ravi: Pass Priya: Fail Arjun: Pass
This program works for these fixed values. But it does not calculate the result.
What happens when Priya scores 75 in the next exam? The program still prints Fail.
What Goes Wrong Without Conditions?
- Fixed results: The program cannot respond to changed marks.
- Repeated code: We must write separate instructions for each student.
- More maintenance: Every new rule needs manual code changes.
- Wrong decisions: The printed result may not match the actual marks.
- Poor scalability: Managing 1,000 students becomes difficult.
Now think about a complete school system. It may process thousands of student records.
We need a way to make decisions using actual values. Conditional statements solve this problem.
The Idea to Remember
- Condition = a question that produces true or false.
- if = run code when a condition is true.
- else = run another block when the condition is false.
- else if = check another condition when the earlier one is false.
- switch = choose one matching option from several choices.
- Ternary operator = choose one of two values using a short expression.
2. The if Statement in C#
The if statement runs a block when its condition is true.
Condition = an expression that returns either true or false.
For example, the school uses 40 marks as the passing mark. We can check whether a student has passed.
Example 2: Check whether a student has passed
using System;
int studentMarks = 82;
if (studentMarks >= 40)
{
Console.WriteLine("Student has passed.");
}
Expected output
Student has passed.
How Does It Work?
- The program stores 82 in
studentMarks. - The
>=operator checks whether marks are at least 40. - The condition returns true because 82 is greater than 40.
- The program enters the
ifblock. - The message appears in the console.
If the condition returns false, the block is skipped. No message is printed by this example.
When Should You Use if?
- Check whether a student is eligible for an exam.
- Check whether an account has enough balance.
- Check whether a user has permission to access a page.
- Check whether a payment amount is valid.
3. The if-else Statement in C#
Sometimes we need two possible outcomes. The if-else statement handles both.
If the condition is true, the first block runs. Otherwise, the else block runs.
Let's check a student's exam result.
Example 3: Display pass or fail
using System;
int studentMarks = 35;
if (studentMarks >= 40)
{
Console.WriteLine("Result: Pass");
}
else
{
Console.WriteLine("Result: Fail");
}
Expected output
Result: Fail
How Does It Work?
- The program reads the student's marks.
- It checks whether the marks are at least 40.
- The condition returns false because the student scored 35.
- The program skips the first block.
- The
elseblock prints the fail message.
Important: The else block is optional. Use it when the false condition needs another action.
4. The else-if Ladder in C#
Schools often use different grade ranges. A simple pass or fail check is not enough.
We can use else if to check several conditions in order.
Let's use these sample grade rules:
- 90 and above: Grade A
- 75 to 89: Grade B
- 60 to 74: Grade C
- 40 to 59: Grade D
- Below 40: Fail
These are sample rules for this article. Actual school grading rules may differ.
Example 4: Assign a grade using else-if
using System;
int studentMarks = 82;
if (studentMarks >= 90)
{
Console.WriteLine("Grade A");
}
else if (studentMarks >= 75)
{
Console.WriteLine("Grade B");
}
else if (studentMarks >= 60)
{
Console.WriteLine("Grade C");
}
else if (studentMarks >= 40)
{
Console.WriteLine("Grade D");
}
else
{
Console.WriteLine("Fail");
}
Expected output
Grade B
How Does the else-if Ladder Work?
- The program checks whether marks are at least 90.
- That condition is false for 82.
- It checks whether marks are at least 75.
- That condition is true, so Grade B is printed.
- The remaining conditions are skipped.
Conditions are checked from top to bottom. The first true condition wins.
Unique Animation 1: Student Result Decision Flow
The animation follows the student's marks through the grade checks. It highlights each tested condition and the first matching result.
5. Nested if Statements in C#
A nested if means an if statement inside another if statement.
Sometimes a student must meet two requirements. For example, the student needs enough marks and attendance.
Let's use these sample rules: at least 40 marks and at least 75 percent attendance.
Example 5: Check exam eligibility using nested if
using System;
int studentMarks = 65;
int attendance = 80;
if (studentMarks >= 40)
{
if (attendance >= 75)
{
Console.WriteLine("Student is eligible.");
}
else
{
Console.WriteLine("Attendance is too low.");
}
}
else
{
Console.WriteLine("Minimum marks not reached.");
}
Expected output
Student is eligible.
How Does It Work?
- The outer condition checks the student's marks.
- The inner condition checks attendance only after marks pass.
- Both conditions must be true for the eligible message.
- If marks fail, the attendance check does not run.
Best practice: Avoid deeply nested conditions. Long nesting makes code harder to read. Consider combining conditions when that makes the rule clearer.
6. The switch Statement in C#
Schools may offer different services through a student portal. A user may choose a menu option.
For example, option 1 shows marks. Option 2 shows attendance. Option 3 shows fee details.
A switch statement checks one value against several possible cases.
Example 6: Student portal menu using switch
using System;
int selectedOption = 2;
switch (selectedOption)
{
case 1:
Console.WriteLine("Showing student marks.");
break;
case 2:
Console.WriteLine("Showing attendance.");
break;
case 3:
Console.WriteLine("Showing fee details.");
break;
default:
Console.WriteLine("Invalid menu option.");
break;
}
Expected output
Showing attendance.
How Does switch Work?
- The program reads the value of
selectedOption. - It compares that value with each case.
- It finds case 2 because the selected value is 2.
- It runs the matching case block.
- The
breakstatement exits the switch block.
The default case runs when no case matches.
Unique Animation 2: switch Menu Routing
The animation shows one menu value entering the switch statement. The matching case is selected while the other choices remain inactive.
What Is the default Case?
The default block is similar to the final else block.
It handles values that do not match any listed case.
Example 7: Handle an invalid menu option
using System;
int selectedOption = 9;
switch (selectedOption)
{
case 1:
Console.WriteLine("Marks");
break;
case 2:
Console.WriteLine("Attendance");
break;
default:
Console.WriteLine("Invalid option");
break;
}
Expected output
Invalid option
7. The Ternary Operator in C#
Sometimes we only need to choose between two values. Writing a full if-else block may feel longer.
The ternary operator provides a shorter expression for this situation.
It uses three parts: a condition, a value for true, and a value for false.
Its syntax looks like this:
Ternary operator syntax
condition ? valueWhenTrue : valueWhenFalse;
Let's use it to display a student's pass or fail result.
Example 8: Find the result using the ternary operator
using System;
int studentMarks = 82;
string result = studentMarks >= 40
? "Pass"
: "Fail";
Console.WriteLine(result);
Expected output
Pass
How Does the Ternary Operator Work?
- The program checks whether marks are at least 40.
- If true, it selects the value
"Pass". - If false, it selects the value
"Fail". - The selected value is stored in the result variable.
- The program prints that value.
Unique Animation 3: Ternary Decision and Value Selection
The animation follows the condition to its selected value. The result then moves into the output step.
Remember: The ternary operator returns a value. It is an expression, not a replacement for every if-else block.
8. Switch Expression in Modern C#
C# also supports switch expressions. They return a value directly.
This can make value selection easier to read. It is useful when each case produces one result.
Here is a grade example using the same school rules.
Example 9: Assign a grade using a switch expression
using System;
int studentMarks = 82;
string grade = studentMarks switch
{
>= 90 => "Grade A",
>= 75 => "Grade B",
>= 60 => "Grade C",
>= 40 => "Grade D",
_ => "Fail"
};
Console.WriteLine(grade);
Expected output
Grade B
The underscore (_) is the discard pattern. Here, it handles every remaining value.
Version note: Switch expressions are available from C# 8.0. This example uses relational patterns, available from C# 9.0.
9. if-else vs switch vs Ternary Operator
Each option solves a different kind of decision. Choose the one that makes your rule easiest to understand.
| Feature | Best use | Example |
|---|---|---|
if |
One condition | Check passing marks |
if-else |
Two possible paths | Pass or fail |
else-if |
Several ordered conditions | Assign a grade |
| Nested if | Dependent conditions | Marks and attendance |
switch |
Several fixed choices | Student portal menu |
| Ternary | Choose one of two values | Pass or fail label |
| Switch expression | Map a value to a result | Marks to grade |
10. Logical Operators with Conditional Statements
Sometimes one decision depends on more than one condition. Logical operators help combine those conditions.
&&means AND. Both conditions must be true.||means OR. At least one condition must be true.!means NOT. It reverses a Boolean value.
Let's check whether a student can attend an examination. The student needs enough marks and attendance.
Example 10: Combine conditions using AND
using System;
int studentMarks = 65;
int attendance = 80;
if (studentMarks >= 40 && attendance >= 75)
{
Console.WriteLine("Eligible for examination.");
}
else
{
Console.WriteLine("Not eligible for examination.");
}
Expected output
Eligible for examination.
Both conditions are true, so the student is eligible under these sample rules.
Using OR for Alternative Requirements
Suppose a student can use a special library facility with either a student ID or an approved visitor pass.
Example 11: Check either valid entry option
using System;
bool hasStudentId = false;
bool hasVisitorPass = true;
if (hasStudentId || hasVisitorPass)
{
Console.WriteLine("Library entry allowed.");
}
else
{
Console.WriteLine("Library entry denied.");
}
Expected output
Library entry allowed.
11. Common Mistakes and Best Practices
Mistake 1: Using = Instead of ==
Use == to compare two values. A single = assigns a value.
Correct comparison
int studentMarks = 82;
if (studentMarks == 82)
{
Console.WriteLine("Marks match.");
}
Mistake 2: Checking Conditions in the Wrong Order
Consider the grade conditions. A check for 40 comes before a check for 90.
A student with 95 marks would match the first condition. The program would print Grade D.
Put more specific or higher-range conditions first when using this grade ladder.
Mistake 3: Forgetting break in a Traditional switch
Use break to leave a traditional switch section. C# does not allow accidental fall-through from one non-empty case section into another.
Switch expressions do not use break.
Mistake 4: Writing Long Nested Conditions
Deep nesting makes the program harder to follow. Combine conditions when the rule remains clear.
For example, use && when both marks and attendance must pass.
Mistake 5: Using Ternary for Complex Logic
Ternary expressions work best for short choices. Long nested ternary expressions are difficult to read.
Use regular if-else blocks when the decision needs several steps.
Best Practices
- Keep conditions simple and easy to understand.
- Use meaningful variable names such as
studentMarks. - Check boundary values such as 39, 40 and 41.
- Use braces even when a block contains one statement.
- Keep the most appropriate condition order.
- Use
switchfor clear fixed choices. - Use ternary only for short value selection.
- Test both true and false paths.
12. Performance and Real-World Considerations
Conditional statements are basic control-flow tools. Their cost is usually small compared with database or network operations.
However, condition order and code structure still matter in large applications.
Condition Order
Conditions in an if-else ladder run from top to bottom. The first matching block runs.
Put common or important checks in a sensible order. Keep business rules correct before trying to optimize them.
Short-Circuit Evaluation
C# uses short-circuit evaluation for && and ||.
With AND, the second condition is skipped when the first is false. The final result is already false.
With OR, the second condition is skipped when the first is true. The final result is already true.
This can avoid unnecessary work. It can also prevent unsafe checks from running.
Keep Business Rules Separate
A small condition can live inside a method. Large business rules should have clear names and tests.
For example, a school application may use a method named IsEligibleForExamination. This makes the rule easier to reuse and test.
Do not place every business rule inside one large controller method.
13. How Conditional Statements Appear in Interviews
Question 1: What Is a Conditional Statement in C#?
What the interviewer wants: They want to know whether you understand decision-making in code.
Strong answer:
"A conditional statement lets a program choose what to execute. It checks a condition that returns true or false. I use if-else for decisions, switch for multiple choices, and ternary for short value selection. For example, a school system can use conditions to calculate student results."
Question 2: What Is the Difference Between if-else and switch?
Strong answer:
"I use if-else when I need to check ranges or complex conditions. I use switch when one value has several fixed choices. For example, marks-based grading fits an if-else ladder. A student portal menu fits a switch statement."
Question 3: What Is the Ternary Operator?
Strong answer:
"The ternary operator is a short way to choose between two values. It checks a condition and returns one of two expressions. I use it for simple assignments, such as storing Pass or Fail. I avoid it when the logic becomes difficult to read."
Question 4: What Is Short-Circuit Evaluation?
Strong answer:
"Short-circuit evaluation means C# may skip the second condition. With AND, it skips the second condition when the first is false. With OR, it skips the second condition when the first is true. This avoids checks that are no longer needed."
Question 5: What Is the Difference Between switch and Switch Expression?
Strong answer:
"A traditional switch runs statements for a matching case. A switch expression returns a value. I use a switch expression when I want to map one input to one result. It can make simple value selection shorter."
What Should Different Experience Levels Explain?
- Junior developer: Explain if, else, switch and ternary with simple examples.
- Senior developer: Explain readability, condition order and short-circuit behavior.
- Technical architect: Explain where business rules belong, how they are tested and how they remain maintainable.
14. Hands-On Practice
Try these exercises using the school example first. Then use different real-life examples.
Beginner: Pass or Fail
Write a program that checks a student's marks. Print Pass for 40 or more. Otherwise, print Fail.
Test values: 25, 40 and 85.
Hint: Use an if-else statement.
Intermediate: Calculate a Grade
Write a program that assigns grades using the sample ranges from this article.
Test values: 95, 82, 68, 45 and 30.
Hint: Use an else-if ladder. Check the highest range first.
Intermediate: Student Portal Menu
Create a menu with these options:
- 1: Show marks
- 2: Show attendance
- 3: Show fee details
- 4: Exit
Hint: Use a switch statement and include a default case.
Advanced: Exam Eligibility
Check whether a student can attend an examination. The student needs at least 40 marks and 75 percent attendance.
Also print a separate message when marks are too low. Print another message when attendance is too low.
Hint: Combine logical operators with if-else statements.
Advanced: Short Result Assignment
Use a ternary operator to assign one of three labels based on a student's marks.
Use "Excellent" for 90 or above. Use "Pass" for 40 to 89. Use "Fail" below 40.
Hint: You can use a nested ternary expression. Keep it readable, or use an if-else ladder instead.
15. Frequently Asked Questions
Can we use multiple else-if blocks?
Yes. You can add multiple else-if blocks. C# checks them in order until one condition is true.
Can an if statement exist without else?
Yes. The else block is optional. Use it only when you need an alternative action.
Can switch check string values?
Yes. A traditional switch can compare strings. String comparisons in switch use case-sensitive matching.
Can we use conditions inside another condition?
Yes. This is called nested conditional logic. Keep nesting limited so the code remains readable.
Is the ternary operator faster than if-else?
Do not choose ternary for assumed speed. Choose it for short, clear value selection. The compiler can optimize both forms.
Can a switch statement have no default case?
Yes. The default case is optional. Add it when unmatched values need handling.
16. Next Steps in the C# Learning Series
You have learned how C# makes decisions using conditions. You also explored if, else, else-if, nested if, switch and ternary expressions.
In the next article, we will learn how to repeat tasks using loops. We will explore for, while and do-while loops.
Previous article: Variables, Data Types and Constants in C#.
Next article: Loops in C# – For, While and Do While.
Share Your Knowledge
Try the exercises and test different input values. Share your approach and discuss alternative solutions. Help other learners understand conditional logic through practical examples.
Learn Technology. Build Your Future.
Upgradix by Shrash Studio – Quality Technology Education. Completely Free.