C# Index Type

In this article, you learn how to use the Index type in C#.

Prior to C# 8, the indexed data structures such as an array or a collection did not have an easier way to get a portion of a collection. The way to get a portion of a collection was to loop through the items or to get the index one item at a time.
 
Indices and ranges provide an easier way to retrieve a range of items in a collection.
 
 
Please note, this feature is available in C# 8 or later versions only. If you’re running the previous versions of Visual Studio 2019, you need to install C# 8.0. If you’re running Visual Studio 2019, you can set the language version of your project by setting Advanced Build Settings.
 
To get to the Advanced Build Properties, Right click on the project name in Solution Explorer > Properties > Build > Advanced > Language version drop down and select version C# 8.0 (beta) from the drop down. 
 

Index type 

 
Index type in C# is a number that can be used for indexing. Index counts a collection items from the beginning. To count a collection items from the end, a prefix (^) operator can be used with an Index.
 
The following code snippet creates two Indices. 
  1. Index idx1 = 2; // 3rd item. Array index starts at 0.  
  2. Index idx2 = ^3; // 3rd item from end  
The following code snippet uses Indices to access items of an array. 
  1. // An array of numbers  
  2. int[] odds = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19};  
  3. // Index types  
  4. Index idx1 = 2; // 3rd item. Array index starts at 0.  
  5. Index idx2 = ^3; // 3rd item from end  
  6. Console.WriteLine($"{odds[idx1]}, {odds[idx2]}");

Range type

 
A Range type can be used on a collection to retrieve items falls within the range. The Range structure in C# represents a range. Range has a start and end index. The range expression x..y can also be used to create a range.
 
The following code snippet applies a range on an array. 
  1. var middleAuthors = authors[2..4];
The following code snippet create a Range and retrieves a range from a collection. 
  1. // An array of strings  
  2. string[] authors = { "Mahesh""Allen""David""Monica""Praveen" };  
  3. // Create a new Range  
  4. Range range = Range.Create(idx1, idx3);  
  5. // Get items for a range  
  6. var middleAuthors = authors[range];  
  7. // var middleAuthors = authors[2..4];  
  8. foreach (string author in middleAuthors)  
  9. Console.WriteLine(author);