Ranges and indices
Another convenient functionality introduced in C# 8 is the new syntax to identify single elements or ranges inside a sequence. The language already offers the ability to get or set elements in an array using the square brackets and a numeric index, but this concept has been extended by adding two operators to identify an item from the end of a sequence and to extract a range between two indices.
In addition to the aforementioned operators, the base class library now offers two new system types, System.Index
and System.Range
, which we will immediately see in action. Let's consider an array of strings containing six country names:
var countries = new[] { "Italy", "Romania", "Switzerland", "Germany", "France", "England" }; var length = countries.Length;
We already know how to use the numeric indexer to get a reference to the first item:
Assert.IsTrue(countries[0] == "Italy");
The...