Control the flow of your program with conditional logic
The if statement executes code if a specified condition is true.
if (condition)
{
// Code to execute if condition is true
}
int temperature = 25;
if (temperature > 20)
{
Console.WriteLine("It's warm outside.");
}
The if-else statement executes one block of code if a condition is true, and another block if it's false.
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
int age = 17;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}
Use if-else if-else to test multiple conditions.
if (condition1)
{
// Code if condition1 is true
}
else if (condition2)
{
// Code if condition2 is true
}
else
{
// Code if all conditions are false
}
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");
}
The switch statement selects one of many code blocks to execute based on an expression's value.
switch (expression)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no cases match
break;
}
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of the work week.");
break;
case "Friday":
Console.WriteLine("Finally, it's Friday!");
break;
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend!");
break;
default:
Console.WriteLine("Midweek day.");
break;
}
C# 8.0 introduced a more concise switch expression syntax:
string result = day switch
{
"Monday" => "Start of week",
"Friday" => "Almost weekend",
"Saturday" or "Sunday" => "Weekend",
_ => "Weekday"
};
The ternary operator is a shorthand for if-else that returns a value based on a condition.
condition ? expression_if_true : expression_if_false;
int number = 10;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(result); // Output: Even
These operators are used in conditions to compare values:
| Operator | Description | Example |
|---|---|---|
| == | Equal to | x == y |
| != | Not equal to | x != y |
| > | Greater than | x > y |
| < | Less than | x < y |
| >= | Greater than or equal to | x >= y |
| <= | Less than or equal to | x <= y |
These operators are used to combine multiple conditions:
| Operator | Description | Example |
|---|---|---|
| && | Logical AND | x > 5 && x < 10 |
| || | Logical OR | x == 5 || x == 10 |
| ! | Logical NOT | !(x > 5) |