C# If...Else and Switch
Conditions let your C# program choose between different actions.
if...else
Example
int marks = 58;
if (marks >= 50)
{
Console.WriteLine("Congratulations, you passed!");
}
else
{
Console.WriteLine("Better luck next time.");
}Congratulations, you passed!
C# programmers usually put each curly brace on its own line, as above. It is a style choice; the code works either way.
else if
Example
int speed = 95;
if (speed > 120)
{
Console.WriteLine("Fine: Rs 5000");
}
else if (speed > 80)
{
Console.WriteLine("Warning: slow down");
}
else
{
Console.WriteLine("Safe speed");
}Warning: slow down
C# checks the conditions from top to bottom and runs only the first block that is true.
Combining Conditions
Use && and || to test more than one thing in a single if:
Example
int age = 21;
bool hasCnic = true;
if (age >= 18 && hasCnic)
{
Console.WriteLine("You can open a bank account");
}You can open a bank account
The Ternary Operator
Example
int stock = 0;
string status = stock > 0 ? "In stock" : "Out of stock";
Console.WriteLine(status);Out of stock
The switch Statement
switch compares one value with many cases. In C#, switch works with numbers, characters and strings:
Example
string city = "Lahore";
switch (city)
{
case "Karachi":
Console.WriteLine("Area code 021");
break;
case "Lahore":
Console.WriteLine("Area code 042");
break;
case "Islamabad":
Console.WriteLine("Area code 051");
break;
default:
Console.WriteLine("Unknown city");
break;
}Area code 042
Unlike C and C++, C# does not let one case fall through into the next by accident. Every case that has code must end with break (or return), or the code will not compile.
Switch Expressions (C# 8+)
A switch expression is a short way to choose a value:
Example
int day = 6;
string type = day switch
{
6 or 7 => "Weekend",
>= 1 and <= 5 => "Weekday",
_ => "Invalid day"
};
Console.WriteLine(type);Weekend
| Part | Meaning |
|---|---|
=> | "gives" the value on the right |
or, and | Combine patterns |
>= 1 and <= 5 | A range pattern |
_ | Matches anything else (like default) |
Exercise
Exercise
What does C# require at the end of a switch case that contains code?
