Conditional statements are one of the most important building blocks in C#. They allow your programs to make decisions based on different conditions, making your applications interactive and dynamic instead of following the same execution path every time.
Imagine you’re building a login system. If the user enters the correct password, access should be granted. Otherwise, the program should display an error message. Or perhaps you’re creating an online store where customers receive discounts only if they spend more than a certain amount. These situations require decision-making, and that’s exactly what the if family of statements is designed for.
In this article, you’ll learn how to use C#’s conditional statements, including if, if...else, else if, nested if statements, and the shorthand ternary operator. You’ll also discover common mistakes to avoid and best practices for writing clean, readable code.
What Are Conditional Statements?
A conditional statement evaluates an expression that produces either true or false.
If the condition is true, one block of code runs. If it’s false, the program either skips that block or executes an alternative block.
For example:
int age = 20;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
Since 20 >= 18 evaluates to true, the message is displayed.
Boolean Expressions
Every if statement relies on a Boolean expression—an expression whose result is either true or false.
Examples include:
5 > 3 // true
10 == 5 // false
20 != 15 // true
You can also store Boolean values in variables.
bool isLoggedIn = true;
if (isLoggedIn)
{
Console.WriteLine("Welcome!");
}
Because isLoggedIn already contains a Boolean value, there’s no need to compare it with true.
Comparison Operators
Comparison operators are commonly used inside conditional statements.
| Operator | Description | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 10 |
> | Greater than | x > 10 |
< | Less than | x < 10 |
>= | Greater than or equal to | x >= 10 |
<= | Less than or equal to | x <= 10 |
Example:
int score = 85;
if (score >= 60)
{
Console.WriteLine("You passed!");
}
Logical Operators
Logical operators combine multiple conditions.
| Operator | Meaning |
|---|---|
&& | AND |
| ` | |
! | NOT |
Example using AND:
int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense)
{
Console.WriteLine("You may drive.");
}
Both conditions must be true.
Example using OR:
bool isAdmin = false;
bool isModerator = true;
if (isAdmin || isModerator)
{
Console.WriteLine("Access granted.");
}
Only one condition needs to be true.
Example using NOT:
bool isBanned = false;
if (!isBanned)
{
Console.WriteLine("Access allowed.");
}
The ! operator reverses the Boolean value.
The if Statement
The if statement executes code only when a condition evaluates to true.
Syntax
if (condition)
{
// Code to execute
}
Example 1
int temperature = 32;
if (temperature > 30)
{
Console.WriteLine("It's a hot day.");
}
Output:
It's a hot day.
Example 2
int number = 8;
if (number % 2 == 0)
{
Console.WriteLine("Even number");
}
The % operator returns the remainder after division. Since 8 % 2 equals 0, the condition is true.
Single Statement vs. Block
An if statement can control a single statement without braces.
if (true)
Console.WriteLine("Hello");
However, braces are strongly recommended.
if (true)
{
Console.WriteLine("Hello");
}
Using braces improves readability and helps prevent bugs when adding more statements later.
The if…else Statement
Use if...else when you want one block of code to execute if the condition is true and another block if it’s false.
Syntax
if (condition)
{
// Executes when true
}
else
{
// Executes when false
}
Example
int age = 16;
if (age >= 18)
{
Console.WriteLine("You can vote.");
}
else
{
Console.WriteLine("You are too young to vote.");
}
Output:
You are too young to vote.
Example: Login
string password = "abc123";
if (password == "Secret123")
{
Console.WriteLine("Login successful.");
}
else
{
Console.WriteLine("Invalid password.");
}
The else if Statement
Sometimes two choices aren’t enough. You may need to evaluate multiple conditions.
That’s where else if comes in.
Syntax
if (condition1)
{
}
else if (condition2)
{
}
else
{
}
Conditions are evaluated from top to bottom.
The first matching condition executes, and the remaining conditions are skipped.
Example: Grading System
int score = 82;
if (score >= 90)
{
Console.WriteLine("Grade A");
}
else if (score >= 80)
{
Console.WriteLine("Grade B");
}
else if (score >= 70)
{
Console.WriteLine("Grade C");
}
else if (score >= 60)
{
Console.WriteLine("Grade D");
}
else
{
Console.WriteLine("Grade F");
}
Output:
Grade B
Example: Shipping Cost
double total = 120;
if (total >= 200)
{
Console.WriteLine("Free shipping");
}
else if (total >= 100)
{
Console.WriteLine("Discounted shipping");
}
else
{
Console.WriteLine("Standard shipping");
}
Why Order Matters
The order of conditions is important.
Incorrect:
if (score >= 60)
{
Console.WriteLine("Passed");
}
else if (score >= 90)
{
Console.WriteLine("Excellent");
}
A score of 95 satisfies the first condition, so "Excellent" is never reached.
Correct:
if (score >= 90)
{
Console.WriteLine("Excellent");
}
else if (score >= 60)
{
Console.WriteLine("Passed");
}
Always place the most specific conditions before the more general ones.
Nested if Statements
An if statement can appear inside another if statement.
Example:
int age = 22;
bool hasLicense = true;
if (age >= 18)
{
if (hasLicense)
{
Console.WriteLine("You may drive.");
}
}
Another example:
bool isLoggedIn = true;
bool isAdmin = false;
if (isLoggedIn)
{
Console.WriteLine("User authenticated.");
if (isAdmin)
{
Console.WriteLine("Administrator panel");
}
}
Nested if statements are useful when one condition depends on another.
Combining Multiple Conditions
You can build more complex expressions.
int age = 30;
bool member = true;
if (age >= 18 && member)
{
Console.WriteLine("Member discount applied.");
}
Using OR:
string role = "Editor";
if (role == "Admin" || role == "Editor")
{
Console.WriteLine("Editing allowed.");
}
Using NOT:
bool completed = false;
if (!completed)
{
Console.WriteLine("Task still pending.");
}
Complex example:
int age = 25;
bool hasTicket = true;
bool vip = false;
if ((age >= 18 && hasTicket) || vip)
{
Console.WriteLine("Entry allowed.");
}
Parentheses make complex conditions easier to read.
The Short Hand If…Else (Ternary Operator)
The ternary operator provides a concise way to choose between two values.
Syntax
condition ? expression1 : expression2;
If the condition is true, expression1 is returned.
Otherwise, expression2 is returned.
Basic Example
Traditional if...else:
int age = 20;
string message;
if (age >= 18)
{
message = "Adult";
}
else
{
message = "Minor";
}
Equivalent ternary expression:
int age = 20;
string message = age >= 18 ? "Adult" : "Minor";
Output:
Adult
Example: Even or Odd
int number = 9;
string result = number % 2 == 0 ? "Even" : "Odd";
Console.WriteLine(result);
Output:
Odd
Example: Discount
double purchase = 150;
double discount = purchase >= 100 ? 0.20 : 0.05;
Console.WriteLine(discount);
Example: Maximum Value
int x = 15;
int y = 20;
int max = x > y ? x : y;
Console.WriteLine(max);
Output:
20
Nested Ternary Operators
A ternary operator can contain another ternary operator.
int score = 75;
string grade =
score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" :
"F";
Although valid, nested ternary expressions quickly become difficult to read.
For complex decision-making, a regular if...else if chain is usually the better choice.
When Should You Use the Ternary Operator?
Use the ternary operator when:
- Choosing between two simple values
- Initializing variables
- Returning a value from a method
- Keeping straightforward code concise
Example:
bool online = true;
Console.WriteLine(online ? "Online" : "Offline");
Avoid using it when multiple statements or complex logic are required.
Instead, use a standard if...else block.
Common Mistakes
Using = Instead of ==
Incorrect:
if (x = 10)
Correct:
if (x == 10)
The = operator assigns a value, while == compares two values.
Forgetting Braces
if (score >= 60)
Console.WriteLine("Passed");
Console.WriteLine("Congratulations!");
Only the first statement belongs to the if.
Better:
if (score >= 60)
{
Console.WriteLine("Passed");
Console.WriteLine("Congratulations!");
}
Writing Redundant Boolean Comparisons
Instead of:
if (isReady == true)
Write:
if (isReady)
Similarly,
Instead of:
if (isReady == false)
Write:
if (!isReady)
Incorrect Condition Order
Always test the most restrictive conditions first.
Poor ordering can make later conditions unreachable.
Best Practices
- Keep conditions simple and easy to understand.
- Use meaningful variable names.
- Prefer braces, even for single statements.
- Avoid deeply nested
ifstatements. - Split complex expressions into smaller Boolean variables when appropriate.
- Use the ternary operator only for simple decisions.
- Place the most specific conditions before broader ones in an
else ifchain.
Real-World Examples
Age Verification
int age = 17;
if (age >= 18)
{
Console.WriteLine("Access granted.");
}
else
{
Console.WriteLine("Access denied.");
}
Student Result
int marks = 88;
if (marks >= 90)
{
Console.WriteLine("Excellent");
}
else if (marks >= 75)
{
Console.WriteLine("Very Good");
}
else if (marks >= 60)
{
Console.WriteLine("Good");
}
else
{
Console.WriteLine("Needs Improvement");
}
Online Store Discount
double total = 240;
bool member = true;
if (member && total >= 200)
{
Console.WriteLine("25% discount");
}
else if (member)
{
Console.WriteLine("10% discount");
}
else
{
Console.WriteLine("No discount");
}
Weather Recommendation
bool raining = true;
bool cold = true;
if (raining && cold)
{
Console.WriteLine("Wear a waterproof jacket.");
}
else if (raining)
{
Console.WriteLine("Take an umbrella.");
}
else
{
Console.WriteLine("Enjoy the weather!");
}
Login Check
string username = "Alice";
string password = "Secret123";
if (username == "Alice" && password == "Secret123")
{
Console.WriteLine("Login successful.");
}
else
{
Console.WriteLine("Invalid username or password.");
}
Summary
Conditional statements enable your C# programs to make decisions based on Boolean expressions. The if statement executes code only when a condition is true, while if...else allows your program to choose between two execution paths. When more than two possibilities exist, else if chains provide an organized way to evaluate multiple conditions in order.
For more advanced scenarios, conditions can be combined with logical operators, and if statements can be nested to express dependent decisions. When the goal is simply to select between two values, the ternary operator (?:) offers a concise alternative to a traditional if...else block.
As your programs grow, prioritize readability over cleverness. Clear conditions, meaningful variable names, consistent use of braces, and well-structured decision logic will make your code easier to understand, debug, and maintain.