if / else (C#)

if and else let a C# program choose between blocks of code based on whether a condition is true. else if checks another condition only when the earlier ones were false.

C#

The condition inside the parentheses must be a bool. Curly braces group the statements that run when the condition is true.

For a quick two-way choice you can use the ternary operator condition ? a : b, and for matching one value against many options a switch is often cleaner.

Syntax

if (condition) { ... } else if (other) { ... } else { ... }

Examples

C#

int score = 75;
if (score >= 90)
    Console.WriteLine("A");
else if (score >= 70)
    Console.WriteLine("B");
else
    Console.WriteLine("C");

Output:

B

Learn it in a lesson

See also

Back to the Dictionary