This blog post is part of series of latest C# 8.0 features. In this post we will explore in detail about the new feature Nullable reference types.
With latest C# 8.0 feature you can use simple expression to slice part of array. Add below code snippet to check this feature.
static void Main(string[] args)
{
string[] characters = {
"Daenerys
Targaryen", "Eddard
Stark", "Catelyn Stark", "Jon Snow", "Sansa Stark", "Arya Stark", "Robb Stark", "Jaime Lannister", "Cersei Lannister"
};
WriteLine("Stark Family:");
foreach (var character in characters[1..7])
{
WriteLine(character);
}
WriteLine();
WriteLine("Starks which are alive:");
Range range = 3..^3;
foreach (var character in characters[range])
{
WriteLine(character);
}
ReadLine();
}
Lets look at below statement first
foreach (var character in characters[1..7])
In above statement it seems like we are iterating over characters from 1 to 7. But if you run the application the value at 7th index is not included in the result. The endpoint is "exclusive" i.e. element at 7 will not be included. Under the hood, ".." is a range expression which is in fact of type Range.
The endpoints of expression don't have to be integers, but they are of type Index and converted to non-negative integers. You can create Index with new ^ operator which defines "from end" so the below statement should return you all elements from array in range 3 to 6.
Range range = 3..^3;
foreach (var
character in characters[range])
What if you want only last 2 characters or Lannister family, you can use below statement to get the ending two elments
range = ^2..;
foreach (var character in characters[range])
Below range expressions are also valid:
Expression
|
Meaning
|
..
|
0..^0
|
2..
|
2..^0
|
..^2
|
0..^2
|
^2..
|
^2..0
|
You can create different combinations and play around with it yourself. In case you specify incorrect range then application will throw ans exception. The range expression will be handy syntax to easily iterate over arrays and more easily readable.
Comments
Post a Comment