Skip to content

Beginner · Decisions, loops and methods · topic 6 of 43 · 30 min

Decisions: if, else, switch and switch expressions

Explanation

if runs a block only when a condition is true, and else if / else handle the other cases. Conditions use comparison operators (==, !=, <, >=) and logical operators (&& and, || or, ! not). A switch picks one of many cases, and the newer switch expression returns a value in a short, readable form.

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.

OperatorMeaningExample (age = 20)Result
==equal toage == 18false
!=not equal toage != 18true
< and >less / greater thanage > 18true
<= and >=less / greater or equalage >= 20true
Careful: In C#, = stores a value and == compares. if (age = 18) does not compile, because age = 18 is an int, not a bool. This rule saves you from a classic C bug.

if, else if, else

csharp
int marks = 72;

if (marks >= 90)
{
    Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
    Console.WriteLine("Grade B");
}
else
{
    Console.WriteLine("Grade C");
}
C# checks from the top and runs only the FIRST block whose condition is true. Shows Grade B.

Combining conditions: && || !

csharp
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");
&& needs both sides true, || needs at least one, ! flips true and false.

&& 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.

Tip: Always use braces { } for if blocks, even for one line. Without braces only the first line belongs to the if, and adding a second line later causes a silent bug.

The ternary operator ? :

csharp
int age = 15;
string ticket = age < 12 ? "Child" : "Adult";
Console.WriteLine(ticket);
condition ? valueIfTrue : valueIfFalse. Shows Adult. Use it for short choices of a value, not for long logic.

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.

csharp
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;
}
Stacked case labels share one block. default runs when nothing else matches.

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.

csharp
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"
};
Arms are checked from top to bottom; the first match wins.
Careful: If no arm matches and there is no _ arm, the program throws an exception at run time, and the compiler warns you that the switch is not exhaustive. Add a _ arm.

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

if · else · switch

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.

csharp
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}");
Shows Fare: Rs 720.00. Real concession rules change; this shows the idea, not the current railway policy.

Practice (0/4 done)

Task 1 · Question

int t = 30; What does this print? if (t > 35) Console.WriteLine("Hot"); else if (t > 25) Console.WriteLine("Warm"); else Console.WriteLine("Cool");

Task 2 · Question

int n = 7; string s = n % 2 == 0 ? "even" : "odd"; What is s?

Task 3 · Question

What does this print? int units = 250; string slab = units switch { <= 100 => "Low", <= 300 => "Medium", _ => "High" }; Console.WriteLine(slab);

Task 4 · Practice

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

Question 1

1.Why does if (x = 5) not compile in C#?

Question 2

2.When is a && b true?

Question 3

3.What does _ mean in a switch expression?

Question 4

4.A switch case has code but no break. What happens?

Question 5

5.string? name = null; Is if (name != null && name.Length > 2) safe?

Read more (free)

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.

From Operators and decisions: if, else and switch

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

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.

From Decisions with if and switch

Which types can a standard C switch use?Related

Answer: Integer types like int, char and enums

Case labels must be integer constants.

From Decisions: if, else and switch

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

  1. 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.
  2. Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.

← Previous: Operators, conversions and parsing input