Skip to content

Conditions, switch and ternary

↑

Examples are independent C# snippets for modern .NET console projects unless noted otherwise. Class declarations and top-level code can live in Program.cs when top-level statements come first.

Control flow chooses which statements execute. Use the simplest structure that communicates the rules correctly.

if checks a boolean expression. An else if adds another test only when earlier conditions are false. A final else handles remaining cases. Order matters when conditions overlap.

Example.cs
int score = 82;
if (score >= 90)
Console.WriteLine("Excellent");
else if (score >= 60)
Console.WriteLine("Passed");
else
Console.WriteLine("Try again");

switch is useful when one value determines several distinct cases. Cases can use pattern matching and guards, but a conventional switch is fine for straightforward menu commands.

Example.cs
string command = "start";
switch (command)
{
case "start": Console.WriteLine("Running"); break;
case "stop": Console.WriteLine("Stopped"); break;
default: Console.WriteLine("Unknown command"); break;
}

The conditional operator condition ? yes : no returns one of two expressions. Use it for small assignments, not complex nested business rules. A switch expression can produce a value from several cases.

Example.cs
int health = 0;
string state = health > 0 ? "Alive" : "Defeated";
string icon = state switch
{
"Alive" => "+",
_ => "x"
};
Console.WriteLine($"{state} {icon}");

An if/else if/else chain tests branches from top to bottom. The first true branch runs; later branches are skipped. Therefore order matters when rules overlap. For example, test score >= 90 before score >= 60 if the first branch represents a higher grade. Include a final else when you must handle values outside the intended ranges.

Use switch when one value selects an action

Section titled “Use switch when one value selects an action”

A switch statement expresses distinct cases for a selected value. A switch expression produces a value and is often clearer than assigning the same variable across many branches. When every possible enum member is important, handle cases explicitly and decide how unknown values should behave rather than silently swallowing them.

Program.cs
int score = 85;
string rank = score switch
{
>= 90 => "Gold",
>= 60 => "Silver",
>= 0 => "Bronze",
_ => "Invalid score"
};
Console.WriteLine(rank); // Silver

This example uses relational patterns. Branches are matched in order, so reversing the first two cases would incorrectly label a score of 95 as Silver.

condition ? whenTrue : whenFalse produces one of two expressions, making it good for a small assignment. Nested ternary expressions quickly become hard to read; use a regular if or a switch expression for more complex rules. A conditional should show business intent rather than maximize the number of statements on one line.

Consider boundaries such as zero, a negative number, an empty input or an unknown enum value. When inputs come from players, files or network messages, validate them before making game-critical changes. A final _ pattern, guard clause, or thrown exception can document what should happen if no expected case matches.

Use if for ranges, switch for known alternatives and ternary for simple two-way expressions.

Check the order of overlapping conditions and avoid deeply nested ternary expressions.

Write a rule that prints Low below 20, Medium below 80 and High otherwise.

Reveal a solution

if (value < 20) ... else if (value < 80) ... else ....