C# - If Else
C# - Conditional Logic with if-else
Section titled “C# - Conditional Logic with if-else”Conditional statements allow your program to execute different blocks of code based on a specified condition. The if-else statement is the most fundamental control flow structure for making decisions in C#.
The if Statement
Section titled “The if Statement”The if statement executes a block of code only if its boolean condition evaluates to true.
int userAge = 20;
if (userAge >= 18){ Console.WriteLine("Access granted. You are an adult.");}
// Output: Access granted. You are an adult.The if-else Statement
Section titled “The if-else Statement”You can add an else block to provide an alternative path of execution when the if condition is false.
Syntax
Section titled “Syntax”if (boolean_expression){ // Executes if the expression is true}else{ // Executes if the expression is false}The flow of control can be visualized as a fork in the road:
( Condition? ) / \ true / \ false / \ (if block) (else block)Example
Section titled “Example”int temperature = 15;
if (temperature > 25){ Console.WriteLine("It's a hot day. Wear shorts!");}else{ Console.WriteLine("It's cool outside. Consider a jacket.");}
// Output: It's cool outside. Consider a jacket.The if-else if-else Chain
Section titled “The if-else if-else Chain”To test multiple conditions in sequence, you can chain else if statements. As soon as one condition is met, its block is executed, and the rest of the chain is skipped.
int score = 85;
if (score >= 90){ Console.WriteLine("Grade: A");}else if (score >= 80){ Console.WriteLine("Grade: B"); // This block will be executed}else if (score >= 70){ Console.WriteLine("Grade: C");}else{ Console.WriteLine("Grade: F");}
// Output: Grade: BModern C# Alternatives for Conditional Logic
Section titled “Modern C# Alternatives for Conditional Logic”Ternary Conditional Operator (?:)
Section titled “Ternary Conditional Operator (?:)”For simple if-else assignments, the ternary operator provides a highly concise syntax. It is an expression that returns a value.
int userAge = 20;
// Syntax: condition ? value_if_true : value_if_false;string status = (userAge >= 18) ? "Adult" : "Minor";
Console.WriteLine($"User status: {status}"); // Output: User status: AdultSwitch Expressions (for Complex Chains)
Section titled “Switch Expressions (for Complex Chains)”For complex if-else if chains that evaluate a single variable, a switch expression is often more readable and less error-prone.
int statusCode = 404;
string message = statusCode switch{ 200 => "OK", 401 => "Unauthorized", 404 => "Not Found", 500 => "Internal Server Error", _ => "Unknown Status Code" // The discard '_' acts as the default case};
Console.WriteLine($"Response: {message}"); // Output: Response: Not FoundBest Practices and Common Pitfalls
Section titled “Best Practices and Common Pitfalls”- Use Braces
{}: Always use curly braces forifandelseblocks, even for a single-line statement. This prevents bugs when adding more lines later. - Avoid Deep Nesting: Deeply nested
ifstatements (arrow code) are hard to read. Refactor them using methods,switchstatements, or guard clauses. - Guard Clauses: Start a method by checking for invalid conditions and exiting early. This flattens your logic.
- Short-Circuiting: Be aware that the logical AND (
&&) and OR (||) operators are “short-circuiting.” InA && B,Bis not evaluated ifAis false. This is useful for preventing errors, e.g.,if (user != null && user.IsAdmin). - Common Error: Using the assignment operator (
=) instead of the equality operator (==) in a condition. C# helps prevent this by requiring aboolin theifcondition, but it’s a classic bug to watch for.