Range Structure in C# 8.0
C# 8.0 introduced a new predefined structure that is known as Range struct. This struct is used to represent a range that has a start and end indexes. It provides a new style to create a range using .. operator. This operator is used to create a range that has a starting and ending index. Also with the help of the Range struct you are allowed to create a variable of the range type.
C#
// C# program to illustrate how to create ranges using System; namespace range_example { class GFG { // Main Method static void Main( string [] args) { int [] marks = new int [] {23, 45, 67, 88, 99, 56, 27, 67, 89, 90, 39}; // Creating variables of range type // And initialize the range // variables with a range // Using .. operator Range r1 = 1..5; Range r2 = 6..8; var a1 = marks[r1]; Console.Write( "Marks List 1: " ); foreach ( var st_1 in a1) Console.Write($ " {st_1} " ); var a2 = marks[r2]; Console.Write( "\nMarks List 2: " ); foreach ( var st_2 in a2) Console.Write($ " {st_2} " ); // Creating a range // Using .. operator var a3 = marks[2..4]; Console.Write( "\nMarks List 3: " ); foreach ( var st_3 in a3) Console.Write($ " {st_3} " ); var a4 = marks[4..7]; Console.Write( "\nMarks List 4: " ); foreach ( var st_4 in a4) Console.Write($ " {st_4} " ); } } } |
Output:
Marks List 1: 45 67 88 99 Marks List 2: 27 67 Marks List 3: 67 88 Marks List 4: 99 56 27
Constructor
Constructor | Description |
---|---|
Range(Index, Index) | This constructor is used to create a new Range instance with the specified starting and ending indexes. |
Properties
Methods
Method | Description |
---|---|
EndAt(Index) | This method is used to create a Range object starting from the first element in the collection to a specified end index. |
Equals() | This method is used to check whether the current range is equal to a specified range. |
GetHashCode() | This method is used to find the hash code for this instance. |
GetOffsetAndLength(Int32) | This method is used to calculate the start offset and length of the given range object with the help of a collection length. |
StartAt(Index) | This method is used to create a new Range instance starting from a specified start index to the end of the collection. |
ToString() | This method returns the string representation of the current Range object. |
Contact Us