Skip to content
Related Articles

Related Articles

Improve Article

Range Constructor in C#

  • Last Updated : 28 Jun, 2021

Range(Index, Index) Constructor is the part of Range Struct. This constructor is used to create a new instance of Range along with the specified starting and ending indexes. When you create a range using the range operator or constructor, then it will not add the last element or end index element. 
For example, we have an array {1, 2, 3, 4, 5, 6 }, now we want to print range[1..3], then it will print 2, 3. It does not print 2, 3, 4.
Syntax: 
 

public Range(Index start, Index end);

Here, the start represents the starting index of the range and the end represents the last index of the range.
Example 1:
 

CSharp




// C# program to illustrate how to
// use Range(Index, Index) constructor
using System;
  
namespace range_example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating and initializing an array
        int[] arr = new int[10] {23, 45, 67, 78,
                        89, 34, 89, 43, 67, 89};
  
        Index start = 2;
        Index end = 5;
  
        // Creating range
        // Using Range(Index,
        // Index) Constructor
        var r = new Range(start, end);
        var value = arr[r];
  
        // Displaying range and elements
        Console.WriteLine("Range: " + r);
        Console.Write("Numbers: ");
  
        foreach(var i in value)
            Console.Write($" {i}, ");
    }
}
}

Output: 
 

Range: 2..5
Numbers:  67,  78,  89, 

Example 2:
 



CSharp




// C# program to illustrate how to
// use Range(Index, Index) constructor
using System;
  
namespace range_example {
  
class Program {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating and initializing an array
        string[] arr = new string[8] {"Archery", "Badminton",
                              "Cricket", "Bowling", "Boxing",
                       "Curling", "Tennis", "Skateboarding"};
  
        // Creating ranges
        // Using Range(Index,
        // Index) Constructor
        var r1 = new Range(0, 3);
        var r2 = new Range(4, 7);
        var value_1 = arr[r1];
        var value_2 = arr[r2];
  
        // Displaying range and elements
        Console.WriteLine("Range: " + r1);
        Console.Write("Sports Name: ");
  
        foreach(var i_1 in value_1)
            Console.Write($" {i_1} ");
  
        Console.WriteLine("\n\nRange: " + r2);
        Console.Write("Sports Name: ");
  
        foreach(var i_2 in value_2)
            Console.Write($" {i_2} ");
    }
}
}

Output:
 

Range: 0..3
Sports Name:  Archery  Badminton  Cricket 

Range: 4..7
Sports Name:  Boxing  Curling  Tennis 

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :