C# Index Type

Introduction

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.

What is Index type?

Index type in C# is a number that can be used for indexing. Index counts a collection of items from the beginning. To count a collection of items from the end, a prefix (^) operator can be used with an Index.

The following code snippet creates two Indices.

Index idx1 = 2;  // 3rd item. Array index starts at 0.
Index idx2 = ^3; // 3rd item from end

The following code snippet uses Indices to access items of an array.

// An array of numbers
int[] odds = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
// Index types
Index idx1 = 2;  // 3rd item. Array index starts at 0.
Index idx2 = ^3; // 3rd item from end
Console.WriteLine($"{odds[idx1]}, {odds[idx2]}");

What is Range type?

A Range type can be used on a collection to retrieve items that fall within the range. The Range structure in C# represents a range. The 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.

var middleAuthors = authors[2..4];

The following code snippet creates a Range and retrieves a range from a collection.

// An array of strings
string[] authors = { "Mahesh", "Allen", "David", "Monica", "Praveen" };
// Define the indices for the range
Index idx1 = 2; // Represents the 3rd item (Array index starts at 0)
Index idx3 = ^1; // Represents the last item
// Create a new Range
Range range = Range.Create(idx1, idx3);
// Get items for the specified range
var middleAuthors = authors[range];
// Print the middle authors
foreach (string author in middleAuthors)
{
    Console.WriteLine(author);
}


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.