typestar

If & else in C#

Branching: the if/else chain and the conditional operator.

int hour = 14;

if (hour < 12)
{
    Console.WriteLine("morning");
}
else if (hour < 18)
{
    Console.WriteLine("afternoon");
}
else
{
    Console.WriteLine("evening");
}

// the conditional operator picks a value, not a branch
var label = hour < 12 ? "am" : "pm";
Console.WriteLine(label);

How it works

  1. if/else if/else runs exactly one branch.
  2. Braces on every branch are the C# habit, even for one-liners.
  3. ? : picks a value inline when a full branch is too much ceremony.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
279
Tokens
65
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 39 seconds.

Type this snippet

Step 1 of 3 in Flow control, step 8 of 29 in Language basics.

← Previous Next →

If & else in other languages