Search⌘ K
AI Features

Conditionals

Explore how to use conditional statements in C# to control program flow based on logical conditions. Learn the syntax and purpose of if-else, else if, switch, and ternary operators. Understand how to apply comparison and logical operators for dynamic boolean expressions, and implement nested conditions in practical examples like checking adult age 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 ...