C# - Decision Making
C# - Decision Making
Section titled “C# - Decision Making”Decision-making structures are the bedrock of programming logic. They allow your program to evaluate conditions and execute different blocks of code based on whether those conditions are true or false. This enables dynamic and responsive application behavior.
The fundamental flow of decision-making is:
1. Test a condition.2. If the condition is TRUE, execute a specific block of code.3. If the condition is FALSE, execute a different block of code (or do nothing).4. Continue with the rest of the program.Conditional Statements in C#
Section titled “Conditional Statements in C#”C# provides a powerful set of statements for handling conditional logic.
| Statement | Description |
|---|---|
| if | Executes a block of code if a specified condition is true. |
| if…else | Executes one block of code if the condition is true, and another if it’s false. |
| if…else if…else | Tests a series of conditions in order and executes the first one that is true. |
| switch | Selects one of many code blocks to be executed based on a pattern match with an expression. |
Ternary Operator (?:) | A shorthand for an if...else statement that returns a value. |
The if, else if, and else Statements
Section titled “The if, else if, and else Statements”These are the most common decision-making statements. They are used to control program flow based on one or more boolean conditions.
Example
Section titled “Example”This example checks the current temperature and provides different feedback. Notice the clear logic and corrected condition in the else if block.
using System;
public class WeatherReport{ public static void Main() { int temperature = 20;
if (temperature < 0) { Console.WriteLine("It's freezing outside!"); } else if (temperature < 15) { Console.WriteLine("It's a cold day. Wear a jacket."); } else if (temperature >= 15 && temperature < 25) { Console.WriteLine("The weather is pleasant."); } else // temperature >= 25 { Console.WriteLine("It's a hot day. Stay hydrated!"); }
Console.WriteLine($"Execution complete. Current temperature was: {temperature}°C"); }}If you compile and execute the code with temperature = 20, the result is:
The weather is pleasant.Execution complete. Current temperature was: 20°CThe switch Statement and Switch Expressions
Section titled “The switch Statement and Switch Expressions”The switch statement is ideal when you have a single variable or expression to test against multiple possible values. Modern C# has significantly enhanced the switch statement with pattern matching and introduced a more concise switch expression.
Example: Classic switch Statement
Section titled “Example: Classic switch Statement”using System;
public class DayOfWeekPrinter{ public static void PrintDay(int day) { switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: case 7: Console.WriteLine("It's the Weekend!"); break; default: Console.WriteLine("Invalid day number!"); break; } }}Example: Modern switch Expression (C# 8.0+)
Section titled “Example: Modern switch Expression (C# 8.0+)”Switch expressions provide a more functional and less verbose syntax, which is perfect for assigning a value based on a condition.
public static string GetDayName(int day){ string dayName = day switch { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", 4 => "Thursday", 5 => "Friday", 6 or 7 => "Weekend", // 'or' pattern _ => "Invalid day" // _ is the discard/default case }; return dayName;}Example: switch with Pattern Matching (C# 9.0+)
Section titled “Example: switch with Pattern Matching (C# 9.0+)”Pattern matching allows switching on types and property values, making it incredibly powerful.
public decimal CalculateToll(object vehicle){ return vehicle switch { Car c when c.Passengers == 0 => 2.00m + 0.50m, // Car with no passengers Car c when c.Passengers == 1 => 2.00m, Car c when c.Passengers == 2 => 2.00m - 0.50m, Car _ => 2.00m - 1.00m, // Any other car Taxi t => 3.50m, Bus b => 5.00m, { } => 4.00m, // Any other non-null object null => throw new ArgumentNullException(nameof(vehicle)) };}
// Dummy classes for the examplepublic class Car { public int Passengers { get; set; } }public class Taxi { }public class Bus { }The Ternary Conditional Operator (?:)
Section titled “The Ternary Conditional Operator (?:)”The ternary operator is a compact, inline if-else statement. It takes three operands: condition ? value_if_true : value_if_false.
Example
Section titled “Example”int userAge = 21;
// Using if-elsestring status;if (userAge >= 18){ status = "Adult";}else{ status = "Minor";}
// Using the ternary operator - much more concisestring ternaryStatus = userAge >= 18 ? "Adult" : "Minor";
Console.WriteLine($"Status from if-else: {status}");Console.WriteLine($"Status from ternary: {ternaryStatus}");Best Practices
Section titled “Best Practices”- Clarity is Key: Prefer
if-elsefor complex logic blocks. Use the ternary operator only for simple, short assignments. - Avoid Deep Nesting: Deeply nested
ifstatements are hard to read and debug. Refactor them into separate methods or use a different control structure. - Use
switchfor Multiple Values: If you are comparing a single variable against 3 or more constant values, aswitchstatement or expression is often cleaner than a longif-else ifchain. - Embrace Pattern Matching: For modern C# development, learn and use pattern matching with
switch. It can dramatically simplify complex conditional logic.