Forum

Learn .Net If Then …
 
Notifications
Clear all

Learn .Net If Then Else statements

1 Posts
1 Users
0 Reactions
9 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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 or false)
  • Watch out for assignment (=) vs. comparison (==) mistakes

.NET’s if-else logic is simple but powerful—it helps your program make decisions dynamically. 


   
Quote
Share: