Index Constructor in C#

A specific type of constructor used to create instances of an index is referred to as an index constructor in C#. Indexes and ranges are introduced as first-class citizens in C# 8.0 and later versions of the language, enabling you to work with data sequences in a more expressive and condensed way. Utilize an index to access elements in a collection or array based on their position. The index constructor must create the Index struct, which represents an index into a sequence. The System namespace contains the Index struct.

Syntax:

It has the following syntax:

public Index (int Value, bool FromEnd = false);
  • Index Constructor:

It is possible to create instances of indices using the constructor of the Index struct. An integer input that indicates the offset from the sequence's end is required by this constructor.

Index myIndex = new Index(4); // Creates an index with an offset of 4 from the end
  • Index With Range:

Indices are frequently used to define a subrange of elements in a sequence when ranges are present. The Range struct, which is also new in C# 8.0, is used to represent ranges.

int[] myArray = { 1, 2, 3, 4, 5 };

Range myRange = 1..4; // Represents a range from index 1 (inclusive) to index 4 (exclusive)

int[] subArray = myArray[myRange]; // Gets a subarray using the range
  • Usage of Arrays and Collections:

In arrays or collections, indices make it simple to access elements. Indexes that are positive indicate the positions at the start of the sequence, while those that are negative indicate the positions at the end.

int[] myArray = { 1, 2, 3, 4, 5 };

Console.WriteLine(myArray[myIndex]); // Accesses the element at the third-to-last position (offset of 4)

C# Code:

Let us take an example to illustrate the index constructor in C#.

using System;

class Program

{

static void Main()

{

// Create an array of integers

int[] myArray = { 10, 20, 30, 40, 50 };

// Create an index with an offset of 4 from the end

Index myIndex = new Index(4);

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {myArray[myIndex]}");

// Create a range from index 1 to index 4 (exclusive)

Range myRange = 1..4;

// Access a subarray using the range

int[] subArray = myArray[myRange];

// Display the elements in the subarray

Console.Write("Subarray elements: ");

foreach (var element in subArray)

{

Console.Write($"{element} ");

}

Console.WriteLine();

}

}

Output:

Element at index 4: 50

Subarray elements: 20 30 40

Example 2:

Let us take another example to illustrate the index constructor in C#.

using System;

class Program

{

static void Main()

{

// Create a list of strings

var myStrings = new string[] { "apple", "banana", "cherry", "date", "elderberry" };

// Create an index with an offset of 3 from the end

Index myIndex = new Index(3);

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {myStrings[myIndex]}");

// Create a range from index 1 to index 4 (exclusive)

Range myRange = 1..4;

// Access a sublist using the range

string[] subList = myStrings[myRange];

// Display the elements in the sublist

Console.Write("Sublist elements: ");

foreach (var element in subList)

{

Console.Write($"{element} ");

}

Console.WriteLine();

}

}

Output:

Element at index 3: date

Sublist elements: banana cherry date

Example 3:

Let us take another example to illustrate the index constructor in C#.

using System;

class Item

{

public string Name { get; set; }

public Item(string name)

{

Name = name;

}

}

class Program

{

static void Main()

{

// Create an array of Item objects

Item[] itemsArray = {

new Item("Item1"),

new Item("Item2"),

new Item("Item3"),

new Item("Item4"),

new Item("Item5")

};

// Create an index with an offset of 2 from the end

Index myIndex = new Index(2);

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {itemsArray[myIndex].Name}");

// Create a range from index 1 to index 4 (exclusive)

Range myRange = 1..4;

// Access a subarray using the range

Item[] subItemsArray = itemsArray[myRange];

// Display the elements in the subarray

Console.Write("Subarray elements: ");

foreach (var item in subItemsArray)

{

Console.Write($"{item.Name} ");

}

Console.WriteLine();

}

}

Output:

Element at index 2: Item3

Subarray elements: Item2 Item3 Item4

Example 4:

using System;

using System.Collections.Generic;

class Customer

{

public string Name { get; set; }

public int Age { get; set; }

public Customer(string name, int age)

{

Name = name;

Age = age;

}

}

class Program

{

static void Main()

{

// Create a string representing a sentence

string sentence = "This is an example sentence for index and range.";

// Create a range to extract a substring

Range myRange = 5..24;

// Access a substring using the range

string subString = sentence[myRange];

// Display the extracted substring

Console.WriteLine("Extracted substring: " + subString);

// Create a list of Customer objects

List<Customer> customers = new List<Customer>

{

new Customer("Alice", 25),

new Customer("Bob", 30),

new Customer("Charlie", 22),

new Customer("David", 28),

new Customer("Eva", 35)

};

// Create an index with an offset of 2 from the end

Index myIndex = ^1;

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {customers[myIndex].Name}, Age: {customers[myIndex].Age}");

}

}

Output:

Extracted substring: is an example sente

Element at index ^1: Eva, Age: 35

Example 5:

using System;

using System.Collections.Generic;

class Product

{

public string Name { get; set; }

public decimal Price { get; set; }

public Product(string name, decimal price)

{

Name = name;

Price = price;

}

}

class Program

{

static void Main()

{

// Create a list of Product objects

List<Product> products = new List<Product>

{

new Product("Laptop", 1200.00m),

new Product("Smartphone", 800.00m),

new Product("Tablet", 400.00m),

new Product("Headphones", 100.00m),

new Product("Camera", 600.00m)

};

// Create an index with an offset of 3 from the end

Index myIndex = new Index(3);

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {products[myIndex].Name} - ${products[myIndex].Price}");

// Create a range from index 1 to index 4 (exclusive)

Range myRange = 1..4;

// Access a sublist using the range

List<Product> subProducts = products.GetRange(myRange.Start.Value, myRange.End.Value - myRange.Start.Value);

// Display the elements in the sublist

Console.WriteLine("Sublist elements:");

foreach (var product in subProducts)

{

Console.WriteLine($"{product.Name} - ${product.Price}");

}

}

}

Output:

Element at index 3: Headphones - $100.00

Sublist elements:

Smartphone - $800.00

Tablet - $400.00

Headphones - $100.00

Example 6:

using System;

class Book

{

public string Title { get; set; }

public string Author { get; set; }

public Book(string title, string author)

{

Title = title;

Author = author;

}

}

class Program

{

static void Main()

{

// Create an array of integers

int[] numbers = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

// Create an index with an offset of 4 from the end

Index myIndex = new Index(4);

// Access an element using the index

Console.WriteLine($"Element at index {myIndex}: {numbers[myIndex]}");

// Create a range from index 2 to the end

Range myRange = 2..;

// Access a subarray using the range

int[] subArray = numbers[myRange];

// Display the elements in the subarray

Console.Write("Subarray elements: ");

foreach (var num in subArray)

{

Console.Write($"{num} ");

}

Console.WriteLine();

// Create a list of Book objects

Book[] books = {

new Book("The Great Gatsby", "F. Scott Fitzgerald"),

new Book("To Kill a Mockingbird", "Harper Lee"),

new Book("1984", "George Orwell"),

new Book("Pride and Prejudice", "Jane Austen"),

new Book("The Catcher in the Rye", "J.D. Salinger")

};

// Create an index with an offset of 2 from the end

Index bookIndex = ^3;

// Access an element using the index

Console.WriteLine($"Book at index {bookIndex}: {books[bookIndex].Title} by {books[bookIndex].Author}");

}

}

Output:

Element at index 4: 50

Subarray elements: 30 40 50 60 70 80 90 100

Book at index ^3: 1984 by George Orwell

Example 7:

// C# program to illustrate

// the use of Index constructor

using System;

namespace example {

class GFG {

static void Main(string[] args)

{

// Creating and initializing an array

string[] greetings = new string[] {"Good Morning", "Hola", "Namaste",

"Bonjour", "Ohayo", "Ahnyounghaseyo"};

// Creating new indexes

// Using Index() constructor

var val1 = new Index(0, true); // Changed to index 0

var val2 = new Index(3, true); // Changed to index 3

var val3 = new Index(2, true); // Changed to index 2

var val4 = new Index(4, false); // Changed to index 4

var val5 = new Index(5, false); // Changed to index 5

var val6 = new Index(1, false); // Changed to index 1

// Getting the values of

// the specified indexes

var res1 = greetings[val1];

var res2 = greetings[val2];

var res3 = greetings[val3];

var res4 = greetings[val4];

var res5 = greetings[val5];

var res6 = greetings[val6];

// Display indexes and their values

Console.WriteLine("Index:{0} Value: {1}", val1, res1);

Console.WriteLine("Index:{0} Value: {1}", val2, res2);

Console.WriteLine("Index:{0} Value: {1}", val3, res3);

Console.WriteLine("Index:{0} Value: {1}", val4, res4);

Console.WriteLine("Index:{0} Value: {1}", val5, res5);

Console.WriteLine("Index:{0} Value: {1}", val6, res6);

}

}

}

Output:

Index:0 Value: Good Morning

Index:3 Value: Bonjour

Index:2 Value: Namaste

Index:4 Value: Ohayo

Index:5 Value: Ahnyounghaseyo

Index:1 Value: Hola

Conclusion:

When working with indices and ranges, the C# index constructor which was first available in C# 8.0 and later versions plays a critical role in improving the expressiveness and readability of code. Developers can create instances of the Index struct that correspond to particular positions within arrays, collections, or sequences by using the index constructor in conjunction with the Index struct. This feature makes it easier to retrieve elements based on their positions, which is particularly useful when working with data that starts or ends a sequence. Index constructors are not just used for numeric indices; they can also be used to represent positions in various data structures in a more flexible and understandable way. In situations where data manipulation and extraction are involved, this feature, along with the range operator, makes it easier to create subarrays and sublists, resulting in more readable and concise code. Regarding handling indices and ranges in code, the index constructor is a useful addition to the C# language, giving programmers greater expressiveness and efficiency.