08. Conditionals
Programs make decisions. Conditionals run a block of code only when a condition is true. C# gives you four tools: if, switch statements, switch expressions, and the ternary ?: operator.
if, else if, else
C# checks each condition from top to bottom and runs the first block whose condition is true. The else block runs when none match. The condition must be a bool: C# does not treat 0 or null as false.
int hour = 14;
if (hour < 12)
{
Console.WriteLine("Good morning");
}
else if (hour < 18)
{
Console.WriteLine("Good afternoon");
}
else
{
Console.WriteLine("Good evening");
}
bool isMember = true;
int price = 100;
if (isMember)
price -= 10;
Console.WriteLine($"Price: {price}");Good afternoon Price: 90
Braces are optional for a single statement, as in the last if. Many teams always use them anyway: adding a second line later without braces is a classic bug.
switch statements
When you compare one value against many options, a switch reads better than a long if chain. Stack several case labels to share one block. Every section must end with break (or return): C# does not let execution fall through to the next case by accident.
var day = DayOfWeek.Saturday;
switch (day)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("Weekend. Sleep in.");
break;
case DayOfWeek.Friday:
Console.WriteLine("Almost there.");
break;
default:
Console.WriteLine("Workday.");
break;
}Weekend. Sleep in.
switch expressions
Most of the time you use a switch to pick a value. A switch expression does exactly that, with far less ceremony. Each arm is pattern => result, and _ matches anything else.
Patterns can be relational (>= 90) and combined with and, or, and not. Arms are checked in order, so put the most specific first.
int score = 84;
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
_ => "F"
};
Console.WriteLine($"Score {score} is grade {grade}");
int month = 7;
string season = month switch
{
12 or 1 or 2 => "Winter",
>= 3 and <= 5 => "Spring",
>= 6 and <= 8 => "Summer",
_ => "Autumn"
};
Console.WriteLine($"July is in {season}");Score 84 is grade B July is in Summer
The ternary operator
condition ? a : b is a one-line if/else that returns a value. Use it for short choices. If you need to nest it, switch to if or a switch expression instead.
int stock = 0;
string label = stock > 0 ? "In stock" : "Sold out";
Console.WriteLine(label);
int items = 1;
Console.WriteLine($"You have {items} {(items == 1 ? "item" : "items")} in your cart");Sold out You have 1 item in your cart
Endpoints decide which HTTP response to send. A missing item becomes a 404, a found one a 200:
app.MapGet("/products/{id}", (int id) =>
{
var product = products.Find(p => p.Id == id);
return product is null ? Results.NotFound() : Results.Ok(product);
});