Beginner · Decisions, loops and methods · topic 6 of 43 · 30 min
Decisions: if, else, switch and switch expressions
Explanation
Why decisions?
Real programs must react differently to different data. A train ticket costs less for a senior citizen. A payment fails if the balance is too low. A decision in code is a place where the program checks a condition and picks a path.
Conditions are bool values
A condition is an expression that gives true or false, a bool. You build it with comparison operators.
| Operator | Meaning | Example (age = 20) | Result |
|---|---|---|---|
| == | equal to | age == 18 | false |
| != | not equal to | age != 18 | true |
| < and > | less / greater than | age > 18 | true |
| <= and >= | less / greater or equal | age >= 20 | true |
if, else if, else
int marks = 72;
if (marks >= 90)
{
Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
Console.WriteLine("Grade B");
}
else
{
Console.WriteLine("Grade C");
}Combining conditions: && || !
int age = 65;
bool hasId = true;
if (age >= 60 && hasId)
Console.WriteLine("Senior citizen discount");
bool isHoliday = false, isSunday = true;
if (isHoliday || isSunday)
Console.WriteLine("Office closed");
if (!hasId)
Console.WriteLine("Please show ID");&& and || are short-circuit operators: if the left side already decides the answer, the right side is not checked. So if (name != null && name.Length > 3) is safe: when name is null, the length check never runs.
The ternary operator ? :
int age = 15;
string ticket = age < 12 ? "Child" : "Adult";
Console.WriteLine(ticket);The switch statement
When you compare one value against many fixed options, a switch is cleaner than a long else-if chain. Each case ends with break (or return). Unlike C and Java, C# does not let one non-empty case fall through to the next.
string day = "Sun";
switch (day)
{
case "Sat":
case "Sun":
Console.WriteLine("Weekend");
break;
case "Fri":
Console.WriteLine("Almost weekend");
break;
default:
Console.WriteLine("Weekday");
break;
}Switch expressions (C# 8 and later)
A switch expression gives back a value. Each line is called an arm: a pattern, an arrow =>, and the result. The underscore _ is the discard pattern, meaning "anything else". With relational patterns (C# 9) you can even compare ranges.
int marks = 83;
string grade = marks switch
{
>= 90 => "A",
>= 75 => "B",
>= 40 => "C",
_ => "F"
};
Console.WriteLine(grade); // B
string day = "Sat";
string kind = day switch
{
"Sat" or "Sun" => "Weekend",
_ => "Weekday"
};Common mistakes and fixes
- Wrong order in else-if chains: checking marks >= 40 before marks >= 90 makes everyone a C. Check the strictest condition first.
- Forgetting break in a switch case: error CS0163, control cannot fall through. Add break or return.
- Comparing strings with different case: "pune" == "Pune" is false. Use string.Equals(a, b, StringComparison.OrdinalIgnoreCase).
- Writing if (x > 5 && < 10): each side needs a full comparison: if (x > 5 && x < 10).
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Decisions: if, else, switch and switch expressions · 1/7
In this lesson your programs learn to make decisions.
Prefer a video by a teacher? Find free videos on “C# if else switch expression pattern matching beginners” on YouTube ↗
In real life: IRCTC-style fare concession
A railway booking app decides the fare based on the passenger. Children under 5 travel free, children up to 11 pay half, and seniors get a concession. A switch expression keeps the rule list short and easy to review.
decimal baseFare = 1200m;
int age = 62;
decimal fare = age switch
{
< 5 => 0m,
<= 11 => baseFare / 2,
>= 60 => baseFare * 0.6m,
_ => baseFare
};
Console.WriteLine($"Fare: Rs {fare:F2}");Practice (0/4 done)
int t = 30; What does this print? if (t > 35) Console.WriteLine("Hot"); else if (t > 25) Console.WriteLine("Warm"); else Console.WriteLine("Cool");
int n = 7; string s = n % 2 == 0 ? "even" : "odd"; What is s?
What does this print? int units = 250; string slab = units switch { <= 100 => "Low", <= 300 => "Medium", _ => "High" }; Console.WriteLine(slab);
Write an electricity bill program. Read the units used. Charge Rs 3 per unit for the first 100 units, Rs 5 per unit for units 101 to 300, and Rs 8 per unit above 300. Print the bill. (Example: 350 units = 100*3 + 200*5 + 50*8 = 1700.)
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while, do-while and foreachDecisions, loops and methods · same module
- Methods: write once, use many timesDecisions, loops and methods · same module
- Parameters in depth: optional, named, ref, out, params, overloadingDecisions, loops and methods · same module
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- Decisions with if and switchGo Programming (backend and cloud) · Control flow and functions
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Why does if (x = 5) not compile in C#?
Answer: x = 5 is an assignment giving an int, and if needs a bool
C# requires a bool condition. Use == to compare.
When is a && b true?
Answer: When both are true
&& (and) needs both sides to be true.
What does _ mean in a switch expression?
Answer: Match anything else (the discard)
The discard pattern _ matches any value not matched earlier.
A switch case has code but no break. What happens?
Answer: Compile error: control cannot fall through
C# does not allow fall-through from a non-empty case (error CS0163).
string? name = null; Is if (name != null && name.Length > 2) safe?
Answer: Yes, because && stops after the first false part
&& short-circuits: when name is null, name.Length is never evaluated.
Which type can NOT be used in a switch?Related
Answer: std::string
switch needs an integral or enum value. Use if / else if for strings.
How many branches of if / else if / else can run?Related
How do you make one switch case match both 1 and 2?Related
Answer: case 1, 2:
List several values separated by commas in one case.
Which types can a standard C switch use?Related
Answer: Integer types like int, char and enums
Case labels must be integer constants.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Decisions, loops and methods” before its exam: Loops: for, while, do-while and foreach, Methods: write once, use many times, Parameters in depth: optional, named, ref, out, params, overloading.
- Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.