advertise with us

Using C# indices and range syntax to access elements in a sequence

Microsofts Indices and Ranges page provides examples of the indices and range syntax available in C# (introduced in C#8). This syntax provides a succinct way to access single elements or ranges in a sequence.

The first example below shows the ‘index from the end’ operator ^, which gives us a shorthand way of getting items relative to the end of a collection. Instead of using collection[collection.Length – 1] to get the last item we can just use ^1.

The second example below shows how we can specify a range of items to slice out from an array (note – slicing like this doesn’t work on Lists<>). Note that when using ranges the upper boundary is exclusive.

C# indices and range syntax


Need Help with Your C# Projects?

We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.

CONTACT US NOW