Search⌘ K
AI Features

Conditionals

Explore the fundamentals of conditionals in C# programming to control the flow of your applications. Understand how to use if else statements, switch cases, logical operators, and the ternary operator to handle multiple conditions. Gain skills to write clear and efficient decision-making code, including checks for age classifications and leap years.

Conditional statements are a basic component of many programming languages. They control program flow depending on given conditions.

The if-else statement

Consider the following scenario. We want to determine if a user is an adult based on their age. A user is an adult if they are 18 or older

Visual example of if-else statement
Visual example of if-else statement

Let’s first create a variable to obtain the user’s age.

Console.Write("What is your age? ");
int age = Convert.ToInt32(Console.ReadLine());
Reading input from the console

We now perform a check. If age is greater than or equal to 18, we print "You are an adult!". Otherwise, we print "You are not yet an adult.".

Such checks can be done using the if-else statement in C#. The basic syntax is as follows:

if (condition)
{
// Actions to be executed if the condition is true
}
else
{
// Actions to be executed if the condition is false
}

The condition must be a boolean expression that evaluates to either true or false.

C# 14.0
bool isAdult = true;
if (isAdult)
{
Console.WriteLine("You are an adult!");
}
else
{
Console.WriteLine("You are not yet an adult.");
}
  • Line 1: Declares a boolean variable isAdult and initializes it to true.

  • Line 3: Checks if isAdult is true.

  • Line 5: Executes this line because the condition is true.

  • Lines 8–10: The else block is skipped because the condition was met.

Change the value of isAdult to false and execute the program once again. This time, the output is different.

Hardcoding boolean values limits program flexibility, so we use operators to generate boolean results dynamically. There are various operators that return a bool value that we can use in checks.

Comparison operators

Comparison operations compare two operands and return a bool value: true if the expression is true, or false if the expression is false.

Comparison operator

Definition

==

This is an equality check. It returns true if the operands are equal to each other. Otherwise, it returns false.

!=

This is an inequality check. It returns true if the operands are not equal to each other. Otherwise, it returns false.

>

This returns true if the first operand is greater than the second operand. Otherwise, it returns false.

<

This returns true if the first operand is less than the second operand. Otherwise, it returns false.

>=

This returns true if the first operand is greater than or equal to the second operand. Otherwise, it returns false.

<=

This returns true if the first operand is less than or equal to the second operand. Otherwise, it returns false.

Equipped with this knowledge of comparison operators, we can now finish our program. When our program needs several conditions and each condition should lead to a different set of actions, we can add else if blocks.

Console.Write("What is your age? ");
int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"You have entered {age}.");

if (age >= 18)
{
    Console.WriteLine("You are an adult!");
}
else if (age < 0) 
{
    Console.WriteLine("Age cannot be negative!");
}
else
{
    Console.WriteLine("You are not yet an adult.");
}
Using comparison operators with else-if blocks
  • Line 2: Converts the input string to an integer.

  • Line 6: Checks if age is greater than or equal to 18.

  • Line 10: If the first condition fails, this checks if age is negative.

  • Line 14: If all previous conditions fail, this default block executes.

Logical operators

There is also a way to chain several bool values using logical operators.

Logical operator

Name

Definition

&&

Logical AND

It returns true if both expressions are true. If the first operand is false, it short-circuits (does not evaluate the second).

||

Logical OR

It returns true if at least one of the expressions is true. If the first operand is true, it short-circuits (does not evaluate the second).

^

Logical XOR

It returns true if only one of the expressions is true. Returns false if both are true or both are false.

!

Logical NOT

It takes only one boolean value as an operand and inverts the value. It returns true if the operand is false, and false if the operand is true.

Let’s change our program a bit so that it also prints whether the user is a teenager. If the user’s age is between 13 and 17 inclusive, they are a teenager.

Console.Write("What is your age? ");
int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"You have entered {age}.");

if (age >= 18)
{
    Console.WriteLine("You are an adult!");
}
else if (age < 0) 
{
    Console.WriteLine("Age cannot be negative!");
}
else if (age < 18 && age >= 13) 
{
    Console.WriteLine("You are a teenager!");
}
else
{
    Console.WriteLine("You are not yet an adult.");
}
Combining conditions with logical operators
  • Line 14: The && operator combines two checks. The code inside this block only runs if age is less than 18 AND age is greater than or equal to 13.

The switch statement

The switch statement is similar to if-else. It allows us to process several conditions in one block more cleanly than multiple else if statements.

Console.Write("Input 5 or 10: ");
int input = Convert.ToInt32(Console.ReadLine());

switch (input)
{
    case 5:
        Console.WriteLine("You have entered 5.");
        break;
    case 10:
        Console.WriteLine("You have entered 10.");
        break;
    default:
        Console.WriteLine("You have entered neither 5 nor 10.");
        break;
}
Using the switch statement
  • Line 4: The variable input is evaluated once.

  • Line 6: If input equals 5, execution jumps here.

  • Line 8: The break statement exits the switch block, preventing execution from “falling through” to the next case.

  • Line 9: If input equals 10, execution jumps here.

  • Line 12: The default block executes if no other case matches, similar to an else block.

The expression compared follows the switch keyword in parentheses. The expression’s value is sequentially compared with the values after the case operator. If a match is found, a specific case block is executed.

Visual example of switch statement
Visual example of switch statement

Every switch case in C# must terminate with a jump statement such as break, goto case, return, or throw. Typically, we use the break statement so that other case blocks are not executed.

Modern pattern matching in switch statements

In modern C#, the switch statement is much more powerful. Instead of just matching exact values (like 5 or 10), we can use relational patterns to evaluate conditions directly inside the case blocks.

C# 14.0
int age = 15;
switch (age)
{
case >= 18:
Console.WriteLine("You are an adult.");
break;
case >= 13 and < 18:
Console.WriteLine("You are a teenager.");
break;
default:
Console.WriteLine("You are a child.");
break;
}
  • Line 5: The case >= 18: pattern checks if the variable is greater than or equal to 18.

  • Line 8: We can use the and keyword (a logical pattern) to combine multiple conditions cleanly.

Ternary operator

The ternary operator is shorthand for the if-else statement. It has the following syntax:

[condition] ? [expression_if_true] : [expression_if_false]

Consider the following code snippet, for example:

Console.Write("What is your age? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"You have entered {age}.");

// The ternary expression evaluates to a string, which is then assigned to 'output'
string output = (age >= 18) ? "You are an adult" : "You are not an adult!";
Console.WriteLine(output);
Using the ternary operator for concise logic
  • Line 6: Evaluates (age >= 18).

    • If true, the expression returns "You are an adult".

    • If false, the expression returns "You are not an adult!".

    • The resulting string is assigned to the variable output.

The ternary operator is often a cleaner alternative to if-else when we have a simple assignment based on a condition.

Note: The ternary operator is designed to return a single value based on a condition. It cannot execute multiple statements or blocks of code like an if-else statement can. If you need to perform multiple actions, such as printing to the console and assigning a variable, you must use a standard if-else block.

Example

Let’s write a program that checks whether a given year is a leap year.

Implementation

A leap year is one that is divisible by four. Exceptions are years that conclude the centuries (2000, 2100, 2200), which must also be divisible by 400.

Our initial version could look like this:

Console.Write("Enter a year: ");
int year = Convert.ToInt32(Console.ReadLine());

// % is the modulo operator. It returns the remainder of the division.
if (year % 4 == 0)
{
    Console.WriteLine($"{year} is a leap year.");
}
else 
{
    Console.WriteLine($"{year} is not a leap year.");
}
Checking divisibility by 4
  • Line 5: The % operator checks if the remainder of year divided by 4 is 0.

Now we need to add further checks. If the year is the end of the century, it must also be divisible by 400. We can have if statements inside other if statements.

Console.Write("Enter a year: ");
int year = Convert.ToInt32(Console.ReadLine());

if (year % 4 == 0)
{
    // year is divisible by 4
    
    // Check if year concludes the century
    if (year % 100 == 0)
    {
        // If it's a century year, it must be divisible by 400 to be a leap year
        if (year % 400 == 0)
        {
            Console.WriteLine($"{year} is a leap year.");
        }
        else 
        {
            Console.WriteLine($"{year} is not a leap year.");
        }
    }
    else 
    {
        // Divisible by 4 but not by 100
        Console.WriteLine($"{year} is a leap year.");
    }
}
else 
{
    Console.WriteLine($"{year} is not a leap year.");
}
Complete leap year logic using nested if statements
  • Line 4: First, checks if the year is divisible by 4.

  • Line 9: Inside the first block, checks if the year is divisible by 100 (a century year).

  • Line 12: If it is a century year, it performs a final check for divisibility by 400.

  • Line 21: Handles the case where the year is divisible by 4 but not by 100 (e.g., 1996, 2024), which means it is a leap year.