How to Create a Range to a Specified End in C#?

The Range Structure is introduced in C# 8.0. It represents a range that has a start and end indexes. You are allowed to a Range object starting from the first element of the specified collection or sequence to a specified end index with the help of EndAt() Method provided by the Range structure. Or in other words, EndAt() method returns a range that starts from the first element of the given collection and ends to the specified index.

Syntax:

public static Range EndAt(Index end);

Here, the Index end represents the end index.



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate how
// to create a range using
// EndAt() method of Range struct
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method 
    static void Main(string[] args)
    {
        // Creating range
        // using Range constructor
        var r1 = new Range(2, 4);
  
        // Creating range
        // using Range operator
        Range r2 = 1..10;
  
        // Creating a range
        // using EndAt() method
        var r3 = Range.EndAt(6);
  
        // Displaying all the ranges
        Console.WriteLine("Range_1: " + r1);
        Console.WriteLine("Range_2: " + r2);
        Console.WriteLine("Range_3: " + r3);
    }
}
}

chevron_right


Output:

Range_1: 2..4
Range_2: 1..10
Range_3: 0..6

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate
// how to create a range using
// EndAt() method of Range struct
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating and initializing an array
        int[] arr = new int[8] {100, 200, 300, 
                     400, 500, 600, 700, 800};
  
        // Creating a range
        // using EndAt() method
        var r = Range.EndAt(5);
        var new_arr = arr[r];
  
        // Displaying the range
        // and the elements
        Console.WriteLine("Range: " + r);
        Console.Write("Numbers: ");
  
        foreach(var i in new_arr)
            Console.Write($" [{i}]");
    }
}
}

chevron_right


Output:

Range: 0..5
Numbers:  [100] [200] [300] [400] [500]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.