C# Ranges

C# Code Snippets Ranges
Share:

About

In this code snippet, we will take a look at ranges in C#.

Ranges give you a quick and easy syntax to get a range/interval of elements from a collection. For example, if an array has 10 elements you can specify a range from the 2nd to the 5th element and that slice of the array will be returned to you.

Let’s have a look at the code below to see how to use ranges.

Code:

string myString = "Hello World!";

//Get substring starting from 3th position on.
Console.WriteLine(myString[3..]);
//Get substring from start till the 3th position.
Console.WriteLine(myString[..3]);
//Get substring from 2rd to 5th position.
Console.WriteLine(myString[2..5]);
//Get substring from start to 2nd position from the end.
Console.WriteLine(myString[..^2]);


Console.WriteLine("");


//The same thing can be applied to arrays.
int[] myArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] myArrayPart = null;

myArrayPart = myArray[3..];
myArrayPart.ToList().ForEach(x => Console.Write(x));
Console.WriteLine();

myArrayPart = myArray[..3];
myArrayPart.ToList().ForEach(x => Console.Write(x));
Console.WriteLine();

myArrayPart = myArray[2..5];
myArrayPart.ToList().ForEach(x => Console.Write(x));
Console.WriteLine();

myArrayPart = myArray[..^2];
myArrayPart.ToList().ForEach(x => Console.Write(x));
Console.WriteLine();

Console.ReadLine();

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger