Skip to content

Selections

Selection statements are used to control the flow of a program based on conditions. The two primary selection statements in C# are if and switch. These statements allow you to execute different blocks of code depending on whether a certain condition is true or false.

If Statements

The if statement is used to execute a block of code if a specified condition is true. It can also be followed by an optional else statement to execute a different block of code if the condition is false.

C#
double grade = 77.4;
char letterGrade = 'F';

if (grade > 90)
{
    letterGrade = 'A';
}
else if (grade > 80)
{
    letterGrade = 'B';
}
else if (grade > 70)
{
    letterGrade = 'C';
}
else if (grade > 60)
{
    letterGrade = 'D';
}            

Console.WriteLine("Final grade: {0}", letterGrade);

Output:

Text Output
Final grade: C

Switch Statements

The switch statement is used to select one of many code blocks to be executed. It is often used when you have multiple possible values to compare.

C#
DateTime date = DateTime.Now;
string message = "";

switch (date.DayOfWeek)
{
    case DayOfWeek.Sunday:
    case DayOfWeek.Saturday:
        message = "It's the weekend!";
        break;
    case DayOfWeek.Monday:
    case DayOfWeek.Tuesday:
        message = "Is it the weekend yet?";
        break;
    case DayOfWeek.Wednesday:
        message = "It's midweek.";
        break;
    case DayOfWeek.Thursday:
    case DayOfWeek.Friday:
        message = "Almost the weekend. :)";
        break;
}

Console.WriteLine("{0}: {1}", date.DayOfWeek, message);

Output:

Text Output
Tuesday: Is it the weekend yet?

Conditional Operator

The conditional (ternary) operator (? :) provides a concise way to express simple if-else statements needed to decide between one of two values.

C#
double grade = 96.2;

Console.WriteLine("You scored {0}. You {1}.", grade, grade > 50 ? "passed" : "failed");

Output:

Text Output
You scored 96.2. You passed.

Further Reading