the core building block for decision-making in your programs.


πŸ“Œ 1. if Statement

The simplest way to make a decision:

int age = 20;
 
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
  • The condition inside () must be a boolean (true or false).

  • Code inside {} runs only if the condition is true.


πŸ“Œ 2. if-else Statement

Add an alternative when the condition is false:

int age = 15;
 
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a minor.");
}

πŸ“Œ 3. if-else if-else Chain

Check multiple conditions in order:

int score = 85;
 
if (score >= 90)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 75)
{
    Console.WriteLine("Grade: B");
}
else if (score >= 60)
{
    Console.WriteLine("Grade: C");
}
else
{
    Console.WriteLine("Grade: F");
}
  • Only the first true condition executes.

  • The else block is optional.


πŸ“Œ 4. Ternary Operator (Short If)

A compact form of if-else:

int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(status); // Adult
  • Syntax: condition ? valueIfTrue : valueIfFalse

  • Useful for simple assignments or inline output.


πŸ“Œ 5. switch Statement

Use switch when you have one variable and multiple discrete cases:

char grade = 'B';
 
switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent");
        break;
    case 'B':
        Console.WriteLine("Good");
        break;
    case 'C':
        Console.WriteLine("Average");
        break;
    default:
        Console.WriteLine("Other");
        break;
}
  • break prevents β€œfall-through” to the next case.

  • default runs if no case matches.

C# 8+ Switch Expressions (modern)

int score = 85;
string result = score switch
{
    >= 90 => "A",
    >= 75 => "B",
    >= 60 => "C",
    _      => "F"
};
Console.WriteLine(result); // B
  • _ is like the default case.

  • Very concise for value-to-value mapping.


πŸ“Œ 6. Logical Operators with Conditions

Combine multiple conditions using:

int age = 20;
bool hasID = true;
 
if (age >= 18 && hasID) // AND
{
    Console.WriteLine("Entry allowed");
}
 
if (age < 18 || !hasID) // OR
{
    Console.WriteLine("Entry denied");
}

βœ… Summary of Conditional Statements

  1. if β†’ simple condition

  2. if-else β†’ two-way decision

  3. if-else if-else β†’ multi-way decision

  4. Ternary ?: β†’ compact if-else

  5. switch β†’ multiple discrete cases

  6. Combine conditions with &&, ||, !