visit
Compared to other languages, C# was way behind in capabilities to handle data efficiently. Well, those days are over now. Microsoft just improved the C# syntax, making it easier for developers to manage data in arrays.
^
, which specifies that an index is relative to the end of the sequence; and..
, which specifies the start and end of a range.Important notes
^0
index is the same as sequence[sequence.Length]
.sequence[^0]
does throw an IndexOutOfRangeException
, just as sequence[sequence.Length]
does.^n
is the same as sequence.Length - n
.[0..0^]
represents the entire sequence, just as [0..sequence.Length]
or [..]
.[..3]
-> give me everything from the start of the array to index 3.[2..]
-> give me everything from index 2 until the end of the array.[..]
-> give me everythingprivate string[] words = new string[]
{
// index from start index from end
"The", // 0 ^9
"quick", // 1 ^8
"brown", // 2 ^7
"fox", // 3 ^6
"jumped", // 4 ^5
"over", // 5 ^4
"the", // 6 ^3
"lazy", // 7 ^2
"dog" // 8 ^1
};
As you can see here
is equal towords[^0]
, which is out of rangewords[9]
Give me some more
Alright, alright. Here are some more ways to use it.var allWords = words[..]; // contains "The" through "dog".
var firstPhrase = words[..4]; // contains "The" through "fox".
var lastPhrase = words[6..]; // contains "the, "lazy" and "dog".
var lazyDog = words[^2..^0]; // contains "lazy" and "dog".
Index
and Range
are also .NET types, which means you can create variables of those types, name them for code clarity, and reuse them over and over.Index the = ^3;
words[the];
Range phrase = 1..4;
words[phrase];
References
Previously published at //blog.miguelbernard.com/c-8-0-indices-and-ranges/