Skip to main content

C# Conditional Statements

In programming, we often need to execute different blocks of code based on certain conditions. This is where conditional statements come in. They allow our programs to make decisions and follow different paths of execution depending on whether specific conditions are true or false.

C# offers several ways to implement conditional logic:

  • if statements
  • if-else statements
  • else if statements
  • switch statements
  • Ternary operator (?:)

Let's explore each of these with examples.

The if Statement

The most basic conditional statement is the if statement. It executes a block of code only if a specified condition evaluates to true.

Syntax

csharp
if (condition)
{
// Code to execute if condition is true
}

Example

csharp
int age = 20;

if (age >= 18)
{
Console.WriteLine("You are an adult.");
}

// Output: You are an adult.

In this example, the message is displayed because the condition age >= 18 evaluates to true.

The if-else Statement

The if-else statement provides an alternative code block to execute when the condition is false.

Syntax

csharp
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}

Example

csharp
int age = 15;

if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}

// Output: You are a minor.

In this example, the second message is displayed because the condition age >= 18 evaluates to false.

The else if Statement

The else if statement allows you to check multiple conditions in sequence.

Syntax

csharp
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
// Code to execute if all conditions are false
}

Example

csharp
int score = 85;

if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}

// Output: Grade: B

In this example, the program checks the score against multiple ranges and assigns a grade accordingly.

Nested if Statements

You can place if statements within other if statements to create more complex conditions.

Example

csharp
bool isLoggedIn = true;
bool isAdmin = false;

if (isLoggedIn)
{
Console.WriteLine("Welcome to the system!");

if (isAdmin)
{
Console.WriteLine("You have admin privileges.");
}
else
{
Console.WriteLine("You have limited access.");
}
}
else
{
Console.WriteLine("Please log in first.");
}

/* Output:
Welcome to the system!
You have limited access.
*/

The switch Statement

The switch statement is useful when you need to compare a single expression against multiple possible values.

Syntax

csharp
switch (expression)
{
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases...
default:
// Code to execute if expression doesn't match any case
break;
}

Example

csharp
int dayOfWeek = 3;
string dayName;

switch (dayOfWeek)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}

Console.WriteLine($"Day {dayOfWeek} is {dayName}");

// Output: Day 3 is Wednesday

Switch Expressions (C# 8.0+)

C# 8.0 introduced a more concise syntax for switch statements called switch expressions.

csharp
int dayOfWeek = 3;
string dayName = dayOfWeek switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
_ => "Invalid day" // The _ is the discard pattern for default
};

Console.WriteLine($"Day {dayOfWeek} is {dayName}");

// Output: Day 3 is Wednesday

The Ternary Operator

The ternary operator provides a shorthand way to write an if-else statement in a single line of code.

Syntax

csharp
condition ? expression_if_true : expression_if_false

Example

csharp
int age = 20;
string message = (age >= 18) ? "You are an adult." : "You are a minor.";
Console.WriteLine(message);

// Output: You are an adult.

This does the same thing as the following if-else statement:

csharp
string message;
if (age >= 18)
{
message = "You are an adult.";
}
else
{
message = "You are a minor.";
}

Real-World Application: Simple Login System

Let's see how we can use conditional statements to create a simple login system:

csharp
string storedUsername = "admin";
string storedPassword = "password123";

Console.WriteLine("=== Login System ===");
Console.Write("Username: ");
string enteredUsername = Console.ReadLine();

Console.Write("Password: ");
string enteredPassword = Console.ReadLine();

if (string.IsNullOrEmpty(enteredUsername) || string.IsNullOrEmpty(enteredPassword))
{
Console.WriteLine("Error: Username and password cannot be empty.");
}
else if (enteredUsername == storedUsername && enteredPassword == storedPassword)
{
Console.WriteLine("Login successful! Welcome, admin.");

// Check admin level
int adminLevel = 2;

switch (adminLevel)
{
case 1:
Console.WriteLine("You have basic admin rights.");
break;
case 2:
Console.WriteLine("You have intermediate admin rights.");
break;
case 3:
Console.WriteLine("You have full admin rights.");
break;
default:
Console.WriteLine("Your admin level is undefined.");
break;
}
}
else
{
Console.WriteLine("Login failed! Incorrect username or password.");
}

/* Sample Output (with correct credentials):
=== Login System ===
Username: admin
Password: password123
Login successful! Welcome, admin.
You have intermediate admin rights.
*/

Real-World Application: Weather Advice Program

Here's another example that uses conditional statements to provide weather advice:

csharp
Console.Write("Enter the current temperature in Celsius: ");
if (double.TryParse(Console.ReadLine(), out double temperature))
{
Console.Write("Is it raining? (yes/no): ");
string isRaining = Console.ReadLine().ToLower();

Console.WriteLine("\nWeather Advice:");

// Temperature advice
if (temperature > 30)
{
Console.WriteLine("- It's very hot! Stay hydrated and try to stay in shade.");
}
else if (temperature > 20)
{
Console.WriteLine("- The temperature is pleasant. Enjoy your day!");
}
else if (temperature > 10)
{
Console.WriteLine("- It's a bit cool. Consider wearing a light jacket.");
}
else if (temperature > 0)
{
Console.WriteLine("- It's cold. Wear a warm coat.");
}
else
{
Console.WriteLine("- It's freezing! Wear warm layers and be careful of ice.");
}

// Rain advice
if (isRaining == "yes")
{
string rainyAdvice = temperature < 0
? "- It might be snowing instead of raining. Drive carefully!"
: "- Don't forget to take an umbrella!";

Console.WriteLine(rainyAdvice);
}
}
else
{
Console.WriteLine("Invalid temperature input!");
}

/* Sample Output:
Enter the current temperature in Celsius: 22
Is it raining? (yes/no): yes

Weather Advice:
- The temperature is pleasant. Enjoy your day!
- Don't forget to take an umbrella!
*/

Summary

Conditional statements are essential for creating dynamic and responsive programs. In this tutorial, we covered:

  • if statements for executing code when a condition is true
  • if-else statements for providing alternative code when a condition is false
  • else if statements for checking multiple conditions in sequence
  • switch statements for comparing an expression against multiple possible values
  • Ternary operator for writing simple if-else statements in a more concise way

By mastering these conditional statements, you can create programs that make decisions and respond differently based on varying inputs and conditions.

Practice Exercises

  1. Create a program that calculates BMI (Body Mass Index) and provides different health advice based on the BMI category.
  2. Write a program that simulates a simple ATM. Allow users to check balance, deposit, or withdraw money with appropriate validations.
  3. Create a simple calculator that can perform addition, subtraction, multiplication, or division based on user input.
  4. Write a program that determines whether a year entered by the user is a leap year.
  5. Create a grading program that takes test scores and assigns letter grades based on the following scale: A (90-100), B (80-89), C (70-79), D (60-69), F (0-59).

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)