This tutorial will show you how to use Range Type in C# 8.0 version
For example in old version C#
static void Main(string[] args)
{
var arrays = new string[]
{
"Product 1",
"Product 2",
"Product 3",
"Product 4",
"Product 5",
"Product 6"
};
for(int i=1; i <= 4; i++)
{
Console.WriteLine(arrays[i]);
}
Console.ReadLine();
}
You can rewrite the code above in C# 8.0 using Range as the following
foreach (var item in arrays[1..3])
{
Console.WriteLine(item);
}
Or you can write from an index to the end
foreach (var item in arrays[1..])
{
Console.WriteLine(item);
}
From the start to an index
foreach (var item in arrays[..3])
{
Console.WriteLine(item);
}
Or Entire range
foreach (var item in arrays[..])
{
Console.WriteLine(item);
}
From index to X from the end
foreach (var item in arrays[1..^1])
{
Console.WriteLine(item);
}
You can install Range Type, then you can write
Range range = 1..4;
foreach (var item in arrays[range])
{
Console.WriteLine(item);
}
Range support two new operators ('^' and '..') which allows building System.Index and System.Range objects and using them to index or slice collections at runtime.