skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Range operator

C# 8

Code card: Range operator. Program output: 4, 5, 6 / Hello / World

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.

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 credit

I may earn a commission if you become a customer.

range.cs
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.cs
4, 5, 6
Hello
World