C# 8 Features: Ranges and Switch Expressions
Introduction
C# 8 introduced several new features to enhance the language. This guide explores two of these features: ranges and switch expressions. Ranges allow you to work with a subset of a collection, and switch expressions provide a more concise and expressive way to handle conditional logic. Sample code is included to illustrate how to use these features.
Ranges in C# 8
Ranges in C# 8 allow you to extract a portion of a collection using the range operator ..
. Key points include:
- Range Operator: Use the
..
operator to define a range, like1..4
, which selects elements from index 1 to 3 (inclusive). - Use with Indexes: Ranges are often used with indexers, making it easier to access a portion of an array or a collection.
- Exclusive End: The end of a range is exclusive, meaning the element at that index is not included.
Switch Expressions in C# 8
Switch expressions provide a concise way to handle conditional logic, and they are more expressive than traditional switch statements. Key points include:
- Expression Syntax: Switch expressions use an expression syntax, allowing you to assign the result to a variable or return it directly.
- Pattern Matching: You can use patterns to match values in switch expressions, making them powerful for complex scenarios.
- Case Expressions: Case expressions are used to define conditions and their corresponding values.
Sample Code
Below are sample C# code snippets that demonstrate the use of ranges and switch expressions.
C# Code (Ranges Example):
using System;
class Program
{
static void Main()
{
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var slice = numbers[2..5]; // Select elements at indices 2 to 4
foreach (var number in slice)
{
Console.WriteLine(number);
}
}
}
C# Code (Switch Expressions Example):
using System;
class Program
{
static void Main()
{
string day = "Friday";
string typeOfActivity = day switch
{
"Monday" => "Work",
"Friday" => "Relax",
_ => "Unknown"
};
Console.WriteLine($"On {day}, you should {typeOfActivity}.");
}
}
Conclusion
C# 8's ranges and switch expressions bring powerful and expressive features to the language. Ranges allow you to work with specific portions of collections, while switch expressions offer a more concise and pattern-based way to handle conditional logic. By incorporating these features into your code, you can improve readability and simplify complex tasks in your C# applications.