Index Struct in C# 8.0
C# 8.0 introduced a new predefined structure that is known as Index struct. This struct is used to represent a type that can be used as an index of a collection or sequence that starts from either start or end. It provides a new index style to access elements that is ^ operator. This operator is used to find the last elements of the specified collection or sequence. Also with the help of Index struct you are allowed to create a variable of the index type.
Example:
// C# program to illustrate // the concept of index using System; namespace example { class GFG { // Main Method static void Main( string [] args) { // Creating and initializing an array int [] num = new int [] {1, 2, 3, 4, 5, 6, 7}; // Accessing the starting // elements of the array Console.WriteLine( "Starting Elements" ); Console.WriteLine(num[1]); Console.WriteLine(num[2]); Console.WriteLine(num[3]); // Accessing the last // elements of the array Console.WriteLine( "Last Elements" ); Console.WriteLine(num[^2]); Console.WriteLine(num[^3]); Console.WriteLine(num[^4]); Console.WriteLine(); // Index as a variable Index i = ^1; Console.WriteLine( "Index as a variable: " + num[i]); } } } |
Output:
Starting Elements 2 3 4 Last Elements 6 5 4 Index as a variable: 7
Constructor
Constructor | Description |
---|---|
Index(Int32, Boolean) | It is used to initialize a new Index with a specified index position and a value that indicates if the index is from the start or the end of a collection. |
Properties
Property | Description |
---|---|
End | It is used to get an Index that points beyond the last element. |
IsFromEnd | It is used to get a value that indicates whether the index is from the start or the end. |
Start | It is used to get an Index that points to the first element of a collection. |
Value | It is used to get the index value. |
Methods
Method | Description |
---|---|
Equals() | It is used to check whether the given index is equal to another index or not. |
FromEnd(Int32) | It is used to create an Index from the end of a collection at a specified index position. |
FromStart(Int32) | It is used to create an Index from the specified index at the start of a collection. |
GetHashCode() | It return the hash code for the given instance. |
GetOffset(Int32) | It is used to calculate the offset from the start of the collection using the given collection length. |
ToString() | It is used to return the string representation of the current Index instance. |
Please Login to comment...