C# is a simple yet powerful language for clearly expressing intent. It comes with a variety of operators that simplify the expression while keeping it easy to understand.
In this article, we’ll dive into the .. (dot-dot) operator, which has been gaining popularity in recent releases.
It is used in the following scenarios:
- .. – Range Operator
- For creating a sub-sequence from an existing sequence, like Substring.
- .. – Spread Element
- To compose a sequence from multiple sequences, like Appending a List.
- .. – Slice Pattern
- To match a sequence to a specific combination, like Slicing the sequence for parallel processing or recursive calls.
Code Example:
using System.Numerics;
int[] odds = [1, 3, 5, 7, 9];
int[] evens = [2, 4, 6, 8];
int[] evenPrime = evens[..1]; // 2 (Open range)
// A sequence of 3 elements starting from Index 1 to 4
// Start index is inclusive, and the end index is exclusive.
var oddPrimes = odds[1..4]; // 3, 5, 7 (Range operator)
// 2, 3, 5, 7
int[] primes = [..evenPrime, ..oddPrimes]; // Spread element
int[] numerals = [0, ..odds, ..evens];
Console.WriteLine(numerals.Order()); // 0, 1, .. 9
Console.WriteLine(Sum(numerals.AsSpan())); // Even more efficient
// Uses a recursive call to compute the sum of the sequence.
// Applies a generic condition to a numeric type.
T Sum<T>(params Span<T> values)
where T : INumber<T>
=> values switch
{
[] => T.Zero, // Empty pattern
[T first, .. var rest] => first + Sum(rest) // Slice pattern
};
Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.