BeginnerLesson 3 of 16
Conditions: if, switch & Co. – C#
Making decisions in code, including with switch expressions.
if/else if/else works like in many languages; the condition goes in parentheses and must be a bool (not 0/1 as in C).
int punkte = 73;
string note;
if (punkte >= 90) note = "excellent";
else if (punkte >= 70) note = "good";
else note = "needs improvement";
Console.WriteLine(note);A more compact way is the ternary operator and the modern switch expression, which returns a value directly:
int alter = 20;
string status = alter >= 18 ? "adult" : "minor";
string tag = 3 switch { 1 => "Mon", 2 => "Tue", 3 => "Wed", _ => "?" };
Console.WriteLine($"{status} {tag}");
int x = 15;
Console.WriteLine(x > 10 && x % 2 == 0); // False
Console.WriteLine(x is > 10 and < 20); // TrueThe classic switch statement needs a break (or return) in every branch, and multiple labels share one block:
string wochentag = "Sun";
switch (wochentag)
{
case "Sat":
case "Sun":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Weekday");
break;
}TipThe logical operators are
&&, || and !. With && and ||, the right-hand side is only evaluated if necessary (short-circuit evaluation).