Introduction
In this article, we are going to learn the new features of C# 8.0, Ranges, and Indices. This introduces new operators and new types - Systems. Index and System.Range.
System.Range
In C#, there is no way to perform the 'slice' or 'ranges' for collections. There is no way to skip and take data without using LINQ methods. So, there's a new way, i.e., using the new range operator 'x..y'. We call this '..' operator the 'Range Operator'. In the above example, 'x' is nothing but the starting index, and 'y' is the ending index. These are also called inclusive and exclusive.
An example of using LINQ to get the elements 2nd, 3rd, and 4th.
An example of using the 'range operator'(x..y) to get the elements 2nd, 3rd, and 4th.
An example of defining this 'x..y' operator with the 'Range' type as follows.
System.Index
This is the second new type introduced in C# 8.0. We have seen a couple of examples about 'Range'. Here, in the 'x..y'(range operator) - x and y are the types of 'Index'. Range internally uses the 'Index' type.
Let's see how to use the Index type with the range operator.
The Hat(^) operator
This is the second new operator introduced in C# 8.0, named the 'Hat'(^) operator. What can we do with this operator? For example - get the last element from the array currently, we are doing like as follows.
Using the hat(^) operator.
Using Ranges for strings to get the substring.
Following are some more examples of using new types and operators.
Example 1. Use Ranges and Index in the array.
Example 2. Exclude the first element.
Example 3. Get the first 3 elements.
Example 4. Exclude the first and last element.
Example 5. Getting substring from the string directly.
You can also download all these examples from here.
Summary
In this article, we discussed what Ranges and Indices in C# 8.0 are and how to use this with examples. If you have any suggestions or queries regarding this article, please contact me.
Stay tuned for other concepts of C# 8.0.
“Learn It, Share it.”