🔄 Using Switch Expressions in Loops in C#
Switch expressions are a powerful feature introduced in C# 8.0 that allow you to write concise and expressive conditional logic. Unlike traditional switch statements, switch expressions return values and can be used inline, making your code cleaner and more readable.
📘 What is a Switch Expression?
A switch expression in C# evaluates an expression and matches it against different patterns or constants. It returns a result based on the matching pattern. This feature enables more compact code, especially when you want to assign a value based on multiple conditions.
🔁 Using Switch Expressions Inside Loops
Often in programming, you process collections of data where each element requires different handling. Combining loops with switch expressions lets you efficiently transform or react to each element’s value in a clear, readable way.
💡 Why Use Switch Expressions in Loops?
- Write concise, expressive conditional logic
- Reduce boilerplate compared to traditional switch statements
- Use functional programming style for better immutability
- Ideal for transforming or categorizing data in collections
📄 C# Example: Switch Expression in a foreach Loop
// Example: Categorizing numbers using switch expressions inside a loop
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List numbers = new() { 3, 8, 15, 22, 35, 42 };
foreach (var num in numbers)
{
string category = num switch
{
< 10 => "Small",
>= 10 and < 20 => "Medium",
>= 20 and < 40 => "Large",
_ => "Extra Large"
};
Console.WriteLine($"Number: {num}, Category: {category}");
}
}
}
📝 Sample Output
Number: 8, Category: Small
Number: 15, Category: Medium
Number: 22, Category: Large
Number: 35, Category: Large
Number: 42, Category: Extra Large
🧠 Explanation
- The
foreach
loop iterates over each number in the list. - The
switch
expression evaluates the number against several range patterns. - Based on the matched pattern, it returns a string category such as "Small", "Medium", etc.
- The result is printed along with the number.
Switch expressions simplify your conditional logic and work well in loops for mapping values to categories, states, or actions. They support pattern matching, relational patterns, and logical conjunctions, enabling highly expressive code.
📚 Additional Notes
- Switch expressions always return a value, making them ideal for assignments inside loops.
- They help avoid verbose syntax and multiple if-else blocks.
- You can combine them with LINQ for even more powerful data transformations.
Post a Comment