C# 8.0 Features (Part 1)
1. Negative Indexing
C# 8.0 allows us to easily retrieve an element from a sequence by specifying how far it is from the end. This feature has been around for years in other programming languages such as Python.
Here is a list of animals sorted by size from smallest to largest:
var animals = new List<string>{ "mouse", "rabbit", "cat", "wolf", "bear", "elephant" };
We can easily retrieve the second-largest animal in the list by doing the following:
var secondLargestAnimal = animals[^2];
This is much more concise than the C# 7 way of doing it:
var secondLargestAnimal = animals[animals.Count-2];
2. Sequence Slicing
C# 8.0 allows us to easily extract a slice of a sequence by specifying the first index and the (non-inclusive) last index. This feature isn’t supported for lists yet, but works great for arrays.
Consider an array of animals sorted by size from smallest to largest:
var animals = new string[]{ "mouse", "rabbit", "cat", "wolf", "bear", "elephant" };
We can easily retrieve an array with only the three smallest animals by doing the following:
var threeSmallest = animals[..3];
Note that the second index specified (3) is not included in the slice.
If we want an array which has all animals larger than the smallest animal, we can do the following:
var allBesidesSmallest = animals[1..];
Slicing can be combined with negative indexing. For example, in order to retrieve all animals besides the largest and smallest animal, we could do the following:
var allBesidesLargestAndSmallest = animals[1..^1];
3. Null-Coalescing Assignment
One frequently comes across code that looks like this:
if (animals== null){ animals = new List<string>(); }
Usually this is because subsequent code cannot handle null for the variable. This code can be shortened with the new null-coalescing assignment operator like so:
animals ??= new List<string();
The null-coalescing assignment operator ??= will assign the right-side operand to the left-side operand if the previous value of the left-side operand is null. If the previous value of the left-side operand is not null, then the right-side operand will not be executed at all.