C# Tutorial menu

C# If...Else and Switch

Conditions let your C# program choose between different actions.

if...else

Example

csharp
int marks = 58;

if (marks >= 50)
{
    Console.WriteLine("Congratulations, you passed!");
}
else
{
    Console.WriteLine("Better luck next time.");
}
Output
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

csharp
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");
}
Output
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

csharp
int age = 21;
bool hasCnic = true;

if (age >= 18 && hasCnic)
{
    Console.WriteLine("You can open a bank account");
}
Output
You can open a bank account

The Ternary Operator

Example

csharp
int stock = 0;
string status = stock > 0 ? "In stock" : "Out of stock";
Console.WriteLine(status);
Output
Out of stock

The switch Statement

switch compares one value with many cases. In C#, switch works with numbers, characters and strings:

Example

csharp
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;
}
Output
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

csharp
int day = 6;

string type = day switch
{
    6 or 7 => "Weekend",
    >= 1 and <= 5 => "Weekday",
    _ => "Invalid day"
};

Console.WriteLine(type);
Output
Weekend
PartMeaning
=>"gives" the value on the right
or, andCombine patterns
>= 1 and <= 5A range pattern
_Matches anything else (like default)

Exercise

Exercise

What does C# require at the end of a switch case that contains code?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp