Conditions: if, switch and Pattern Matching
if, else if, else
csharp
int score = 78;
if (score >= 90)
{
Console.WriteLine("Grade A");
}
else if (score >= 75)
{
Console.WriteLine("Grade B");
}
else
{
Console.WriteLine("Grade C");
}
Result
Grade B
C# checks the conditions from top to bottom and runs the first block that is true.
Combining Conditions
csharp
int age = 20;
bool hasTicket = true;
if (age >= 18 && hasTicket)
Console.WriteLine("Welcome");
if (!hasTicket || age < 18)
Console.WriteLine("Sorry, no entry");
| Operator | Meaning |
|---|---|
&& | AND: both must be true |
|| | OR: at least one is true |
! | NOT: reverses true and false |
The Ternary Operator
csharp
string result = score >= 50 ? "Pass" : "Fail";
switch Statement
csharp
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 6:
case 7:
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Another weekday");
break;
}
Every case needs break: Unlike some languages, C# does not allow 'falling through' from one case into the next. End each case with
break, return or similar.
switch Expression (Modern)
A shorter way to pick a value:
csharp
string DayName(int day) => day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
6 or 7 => "Weekend",
_ => "Another weekday" // _ means 'anything else'
};
Console.WriteLine(DayName(3)); // Wednesday
Pattern Matching
Patterns let you test the shape of data in a readable way.
csharp
string Grade(int score) => score switch
{
>= 90 => "A",
>= 75 => "B",
>= 50 => "C",
_ => "F"
};
object value = 42;
if (value is int number && number > 10)
Console.WriteLine($"Big integer: {number}");
if (value is not string)
Console.WriteLine("It is not text");
string Describe(object o) => o switch
{
null => "nothing",
int i => $"integer {i}",
string s => $"text of length {s.Length}",
_ => "something else"
};
| Pattern | Example |
|---|---|
| Relational | >= 90 |
| Logical | > 0 and < 10, 1 or 2, not null |
| Type | int i, string s |
| Property | { Length: 0 } |
When to use which: Use
if for general conditions, a switch expression when you map one value to another.
Conclusion
if handles general decisions, switch picks between many values and patterns make the code short and readable.
Quick Summary: if/else for conditions, switch expressions for value mapping, patterns like >= 90 and is not null.

