← Zurück zum Kurs: C# from scratch

Decisions with if, else and the ternary operator

Video folgt in Kürze

A program that always does the same thing is not very useful. The point is that it reacts to data: if the person is an adult, if the password matches, if the stock is enough. That is what the if statement is for: it runs a block of code only when a condition is true. The condition must be a bool expression, exactly the ones you learned to build with comparison and logical operators. In C# there is no idea of a "truthy value" as in other languages: an int or a string does not work as a condition, it has to be a real bool.

if, else if and else

The full form is if (condition) { ... } else if (another condition) { ... } else { ... }. C# checks the conditions from top to bottom and runs only the first block whose result is true; the final else catches everything that matched nothing. That is why order matters: if you put the most general condition first, the others are never reached. Braces are optional when the block has a single line, but you should always write them, because adding a second line without braces is a classic source of bugs that are hard to see.

csharp
int score = 72;

if (score >= 90)
{
    Console.WriteLine("Excellent");
}
else if (score >= 70)
{
    Console.WriteLine("Good");        // this one runs
}
else if (score >= 50)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Try again");
}

// Wrong order: the first condition catches everything >= 50
if (score >= 50) Console.WriteLine("Pass (too general)");
else if (score >= 70) Console.WriteLine("Never reached");

Nested and combined conditions

You can put an if inside another one, but too many levels make code unreadable. It is almost always better to combine conditions with && and ||, or to use guard clauses: check first what is wrong and finish early, so the normal path stays without indentation. In a top-level program you can finish with return, which ends the program. Another practical tool is to store a complex condition in a bool variable with a clear name, such as isEligible. The name explains the intention much better than a line with five operators.

csharp
int age = 17;
bool hasParent = true;
decimal balance = 25m;

// guard clause style
if (balance <= 0)
{
    Console.WriteLine("No money");
    return;
}

bool isEligible = age >= 18 || (age >= 16 && hasParent);
if (isEligible)
{
    Console.WriteLine("Can buy the ticket");   // this one prints
}

// comparing strings
string answer = "YES";
if (string.Equals(answer, "yes", StringComparison.OrdinalIgnoreCase))
{
    Console.WriteLine("Confirmed");
}

The ternary operator

When you only need to choose between two values, the ternary operator condition ? valueIfTrue : valueIfFalse sums up a whole if in one line. It is perfect for simple assignments, such as choosing a text depending on a number. If you start nesting ternaries inside each other, go back to a normal if: readability is worth more than saving lines. Also, to check for a null value there is the ?? operator, which you will see in week 5.

csharp
int items = 3;
string label = items == 1 ? "item" : "items";
Console.WriteLine($"{items} {label}");     // 3 items

int temperature = 31;
string message = temperature > 30 ? "Hot" : "Fine";
Console.WriteLine(message);                // Hot

Teste dein Wissen

Frage 1 von 2

What type must the condition of an if have in C#?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →