Ranges and indices

C# 8 comes with ranges, which allow you to take a slice of an array or string. Before, if you wanted to get only the first three numbers of an array, you had to iterate through the array and use a condition to find out which values you wanted to use. Let's take a look at an example:

using System;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
var numbers = new int[] { 1, 2, 3, 4, 5 };
foreach (var n in numbers)
{
if(numbers[3] == n) { break; }
Console.WriteLine(n);
}
Console.ReadKey();
}
}
}

With ranges, you can easily slice the array and take whatever value you want, as shown in the following code:

using System;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
var numbers = new int[] { 1, 2, 3, 4, 5 };
foreach (var n in numbers[0..3])
{
Console.WriteLine(n);
}
Console.ReadKey();
}
}
}

In the preceding example, we can see that we gave a range ([0..3]in the foreach loop next to the numbers. This means that we should only take the values of index 0 to index 3 in the array.

There are other ways to slice an array. You can use ^ to say that indexes should be taken backward. For example, if you want to get values from the second element to the second-from-last element, you can use [1..^1]. If you apply this, the result you will get is 2, 3, 4.

Let's take a look at the use of ranges in the following code:

using System;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
var numbers = new int[] { 1, 2, 3, 4, 5 };
foreach (var n in numbers[1..^1])
{
Console.WriteLine(n);
}
Console.ReadKey();
}
}
}

When running the above code you will be needing a special nuget package in your project. The name of the package is Sdcb.System.Range. To install this package you can go to Nuget Package Manager in Visual Studio and install it.

Figure: Installing Sdcb.System.Range nuget package

If you are still having build errors there is a possibility that your project is still using C# 7 and to upgrade to C# 8 you hover over the place which is marked with red underline and click the light bulb that will popup. Then the Visual Studio will ask if you want to use C# 8 for your project. You need to click on Upgrade this project to C# language version '8.0 *beta*'. This will upgrade your project from C# 7 to C# 8 and you will be able to run your code.

Figure: Upgrade project to C# 8
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.76.44