Tip #015
Range operator
About this tip
A range's start is inclusive and its end is exclusive. It slices arrays and strings alike. It works on arrays and strings, and either side can be left open. It is available since C# 8. The key line is Range range = 3..6 in range.cs.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffee
Railway
Referral
Need somewhere to deploy?
My link gets you $20 in credits.
Claim $20 creditI may earn a commission if you become a customer.
Code
int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
Range range = 3..6;var middle = numbers[range];Console.WriteLine(string.Join(", ", middle));
var text = "Hello, World";Console.WriteLine(text[..5]);Console.WriteLine(text[7..]);Output
$ dotnet run range.cs4, 5, 6HelloWorld