🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME 01POSTS 02COURSES 03ELECTRİCAL_ENERGY 04AUTOMOTİVE_ENGİNEERİNG 05TOOLS 06LAB 07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Conditions: if, switch and the switch Expression

Learn to make your program decide: if/else if/else, the classic switch, the modern switch expression and the ternary operator.

Decisions and bool

A program does not always run straight from top to bottom; sometimes it branches onto different paths depending on the situation. Conditions provide these branches. A condition is an expression whose result is true or false (the comparison operators from the last lesson).

if, else if, else

Let us convert an ADC (analog-to-digital converter) reading into a voltage and print a message depending on the case. A 10-bit ADC produces values from 0 to 1023, and let the reference voltage be 5 V: voltage = adc * 5.0 / 1023.

int adc = 700;
double voltage = adc * 5.0 / 1023;

if (voltage < 1.0)
{
    Console.WriteLine("Low level");
}
else if (voltage < 3.5)
{
    Console.WriteLine("Normal level");
}
else
{
    Console.WriteLine("High level");
}
Console.WriteLine($"Measured: {voltage:F2} V");
Normal level
Measured: 3.42 V

The calculation: 700 × 5 / 1023 = 3.4213..., which is greater than 1.0 and less than 3.5, so the second branch runs.

Conditions are tried from top to bottom; the first one that is true runs and the rest are skipped. That is why arranging ranges from small to large makes your job easier.

Tip: You can leave out the curly braces for a one-line body, but don't. It is the most common mistake when you add a second line later.

The classic switch

If you are going to check which of several fixed values a variable equals, switch is more readable.

int day = 6;

switch (day)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        Console.WriteLine("Weekday");
        break;
    case 6:
    case 7:
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Invalid day");
        break;
}

Every case must end with a break. Empty cases stacked one under the other share the same code. If none of them matches, default runs.

The switch expression (modern)

The switch expression, which arrived with C# 8, produces a value and is much shorter. You can also write ranges with relational patterns (<, >=):

double temperature = 31.5;

string status = temperature switch
{
    < 0   => "Freezing",
    < 25  => "Cool",
    < 40  => "Hot",
    _     => "Dangerous"
};

Console.WriteLine($"{temperature} degrees: {status}");
31.5 degrees: Hot

The underscore _ means "everything else". The arms are tried from top to bottom; that is why the < 25 arm does not need to cover values below 0, because those were already caught first.

The ternary operator

A short form for simple two-way decisions: condition ? ifTrue : ifFalse.

int age = 17;
string message = age >= 18 ? "Adult" : "Not an adult";
Console.WriteLine(message);

Warning: Nesting ternary operators makes code unreadable. If there are three or more options, use if/else if or a switch expression.

Try it yourself

Write a program that takes an average grade (0-100) from the user and gives a letter grade, first with if/else if and then with a switch expression: 90 and above is AA, 80 and above is BA, 70 and above is BB, 60 and above is CC, below that is FF. Give an error message for an invalid grade (less than 0 or greater than 100).

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What does the "_" arm mean in a switch expression?
2. What happens when more than one condition is true in an if / else if chain?
3. What must be at the end of each case in a classic switch?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.