Notifications
Clear all
Topic starter 01/08/2025 11:45 pm
In .NET (especially in C#), if-else
statements are a fundamental way to control the flow of your program—executing different blocks of code depending on whether a condition is true or false.
🏁 Basic Syntax
if (condition)
{
// Code to run if condition is true
}
else
{
// Code to run if condition is false
}
✅ Example
int age = 20;
if (age >= 18)
{
Console.WriteLine("You're an adult.");
}
else
{
Console.WriteLine("You're a minor.");
}
🔀 else if
for Multiple Conditions
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else
{
Console.WriteLine("Keep studying!");
}
⚡ One-Liner Shortcut (Ternary Operator)
string result = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(result);
🛡 Safety Tips
- Always use
{}
curly braces for clarity—even for one-liners - Conditions must evaluate to a Boolean value (
true
orfalse
) - Watch out for assignment (
=
) vs. comparison (==
) mistakes
.NET’s if-else
logic is simple but powerful—it helps your program make decisions dynamically.