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
if/else if/elseruns exactly one branch.- Braces on every branch are the C# habit, even for one-liners.
? :picks a value inline when a full branch is too much ceremony.
Keywords and builtins used here
elseifintvar
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.
Step 1 of 3 in Flow control, step 8 of 29 in Language basics.