C# If...Else

Making decisions in your code

🔀 What is If...Else?

If...Else statements allow your program to make decisions and execute different code based on conditions. They check if something is true or false and respond accordingly.


// Simple if statement
int age = 20;
if (age >= 18)
{
    Console.WriteLine("You are an adult");
}
                                    

Output:

You are an adult

Conditional Statements

➡️

If Statement

Execute code if condition is true

if (x > 10)
{
    Console.WriteLine("Big");
}
↔️

If...Else

Choose between two options

if (x > 10)
    Console.WriteLine("Big");
else
    Console.WriteLine("Small");
🔄

Else If

Check multiple conditions

if (x > 10)
    Console.WriteLine("Big");
else if (x > 5)
    Console.WriteLine("Medium");
🎯

Nested If

If statements inside if statements

if (x > 0)
{
    if (x < 10)
        Console.WriteLine("1-9");
}

🔹 The If Statement

The C# if statement is the fundamental conditional construct that directs program flow based on boolean logic. It evaluates a specified condition; if the result is true, the code block within the statement executes. If the condition is false, the block is entirely skipped, and the program continues sequentially. This allows for dynamic decision-making, such as validating user input, controlling application features, or implementing business rules, forming the basis of all responsive and logical program behavior.

int temperature = 30;

if (temperature > 25)
{
    Console.WriteLine("It's hot outside!");
}

// Multiple statements in if block
int score = 95;
if (score >= 90)
{
    Console.WriteLine("Excellent work!");
    Console.WriteLine("You got an A grade");
}

Output:

It's hot outside!

Excellent work!

You got an A grade

🔹 The Else Statement

The else statement extends the if construct by defining an alternative execution path when the initial condition is false. It creates a binary decision structure, ensuring that exactly one of two code blocks will run. This is essential for handling mutually exclusive outcomes, like pass/fail checks, access grants/denials, or true/false responses, making programs more comprehensive and capable of managing both expected and alternative scenarios with clear, structured logic.

int age = 15;

if (age >= 18)
{
    Console.WriteLine("You can vote");
}
else
{
    Console.WriteLine("You cannot vote yet");
}

// Another example
bool isRaining = false;
if (isRaining)
{
    Console.WriteLine("Take an umbrella");
}
else
{
    Console.WriteLine("Enjoy the sunshine!");
}

Output:

You cannot vote yet

Enjoy the sunshine!

🔹 The Else If Statement

The else if statement enables sequential evaluation of multiple exclusive conditions within a single decision structure in C#. The program tests each else if condition in order, executing the block corresponding to the first true condition encountered. This is ideal for multi-stage classifications like grading systems, tiered pricing, or menu-driven logic, providing a cleaner and more efficient alternative to nesting multiple separate if statements and improving code readability and maintainability.

int score = 75;

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: C

🔹 Nested If Statements

Nested if statements allow for complex, hierarchical decision-making by placing conditional blocks inside other conditionals in C#. This structure is used when a secondary decision depends on the outcome of a primary condition, such as checking eligibility and then verifying specific criteria within that group. While powerful, excessive nesting can reduce readability; thus, it should be used judiciously to model dependent logical relationships clearly, such as multi-step authentication or layered validation rules.

int age = 25;
bool hasLicense = true;

if (age >= 18)
{
    Console.WriteLine("You are old enough to drive");
    
    if (hasLicense)
    {
        Console.WriteLine("You can drive legally");
    }
    else
    {
        Console.WriteLine("You need to get a license first");
    }
}
else
{
    Console.WriteLine("You are too young to drive");
}

Output:

You are old enough to drive

You can drive legally

🔹 Short Hand If (Ternary Operator)

The ternary operator is a concise way to write single if...else statements in one line. It has the structure: condition ? expressionIfTrue : expressionIfFalse. For example, int result = (x > y) ? x : y; assigns the larger value. This operator improves readability for simple conditional assignments but should be avoided for complex logic where traditional if-else blocks are clearer. It's widely used for inline value selection and simple checks.

// Traditional if-else
int age = 20;
string result;
if (age >= 18)
{
    result = "Adult";
}
else
{
    result = "Minor";
}
Console.WriteLine(result);

// Ternary operator (shorter)
int age2 = 20;
string result2 = (age2 >= 18) ? "Adult" : "Minor";
Console.WriteLine(result2);

// Another example
int number = 10;
string type = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine($"{number} is {type}");

Output:

Adult

Adult

10 is Even

🔹 Practical Examples

While loops are fundamental for real-world programming tasks where repetition is conditional. Key applications include input validation (re-prompting a user until correct data is entered), accumulating a sum until a threshold is met, implementing password attempts with limited tries, or running a main game loop. Their flexibility makes them suitable for event-driven programming, processing streams of data, and controlling program states where the exact number of required repetitions cannot be predetermined before runtime.

// Login validation
string username = "admin";
string password = "pass123";

if (username == "admin" && password == "pass123")
{
    Console.WriteLine("Login successful!");
}
else
{
    Console.WriteLine("Invalid credentials");
}

// Discount calculator
double price = 100;
double discount = 0;

if (price >= 100)
{
    discount = price * 0.20; // 20% discount
    Console.WriteLine($"You get a ${discount} discount!");
}
else
{
    Console.WriteLine("No discount available");
}

// Time-based greeting
int hour = 14;

if (hour < 12)
{
    Console.WriteLine("Good morning!");
}
else if (hour < 18)
{
    Console.WriteLine("Good afternoon!");
}
else
{
    Console.WriteLine("Good evening!");
}

Output:

Login successful!

You get a $20 discount!

Good afternoon!

🧠 Test Your Knowledge

What will be printed if x = 5?
if (x > 10) Console.WriteLine("A"); else Console.WriteLine("B");