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 (trueorfalse). -
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
elseblock 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;
}-
breakprevents βfall-throughβ to the next case. -
defaultruns 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 thedefaultcase. -
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
-
ifβ simple condition -
if-elseβ two-way decision -
if-else if-elseβ multi-way decision -
Ternary
?:β compactif-else -
switchβ multiple discrete cases -
Combine conditions with
&&,||,!