Open In App

Range and Indices in C# 8.0

Last Updated : 28 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

As we already know about the Range and Indices. We use them several times in our programs, they provide a short syntax to represent or access a single or a range of elements from the given sequence or collections. In this article, we will learn what’s newly added in the range and indices in C# 8.0. In C# 8.0, the following new things are added in the range and indices:

1. Two New Types:

  • System.Range: It represents a sub-range of the given sequence or collection.
  • System.Index: It represents an index into the given sequence or collection.

2. Two New Operators:

  • ^ Operator: It is known as the index from the end operator. It returns an index that is relative to the end of the sequence or collection. It is the most compact and easiest way to find the end elements compare to earlier methods.
    // Old Method
    var lastval = myarr[myarr.Length-1]
    
    // New Method
    var lastval = myarr[^1]
    

    Example:




    // C# program to illustrate the use 
    // of the index from end operator(^)
    using System;
      
    namespace example {
      
    class GFG {
      
        // Main Method
        static void Main(string[] args)
        {
            // Creating and initializing an array
            int[] myarr = new int[] {34, 56, 77, 88, 90, 45};
      
            // Simple getting the index value
            Console.WriteLine("Values of the specified indexes:");
            Console.WriteLine(myarr[0]);
            Console.WriteLine(myarr[1]);
            Console.WriteLine(myarr[2]);
            Console.WriteLine(myarr[3]);
            Console.WriteLine(myarr[4]);
            Console.WriteLine(myarr[5]);
      
            // Now we use index from end(^) 
            // operator with the given index
            // This will return the end value
            // which is related to the specified
            // index
            Console.WriteLine("The end values of the specified indexes:");
            Console.WriteLine(myarr[^1]);
            Console.WriteLine(myarr[^2]);
            Console.WriteLine(myarr[^3]);
            Console.WriteLine(myarr[^4]);
            Console.WriteLine(myarr[^5]);
            Console.WriteLine(myarr[^6]);
        }
    }
    }

    
    

    Output:

    Values of the specified indexes:
    34
    56
    77
    88
    90
    45
    The end values of the specified indexes:
    45
    90
    88
    77
    56
    34
    

    Explanation: In the above example, we have an array of int type named myarr. Here, first we simply get the values of the specified index that is:

    34, 56, 77, 88, 90, 45
    Index : Value
     [0]  : 34
     [1]  : 56
     [2]  : 77
     [3]  : 88
     [4]  : 90
     [5]  : 45
    
    

    Now we find the last value of the specified index with the help of ^ operator that is:

    Index : Value
     [^1]  : 45
     [^2]  : 90
     [^3]  : 88
     [^4]  : 77
     [^5]  : 56
     [^6]  : 34
    

    Important Points:

    • The working of this operator is similar to myarr[arr.Length].
    • You are not allowed to use myarr[^0] if you use this, then this will throw an error because the end index starts from ^1, not from ^0 as shown in the below example:

      Example:




      // C# program to illustrate the use 
      // of the index from end operator(^)
      using System;
        
      namespace example {
        
      class GFG {
        
          // Main Method
          static void Main(string[] args)
          {
              // Creating and initializing an array
              int[] myarr = new int[] {34, 56,
                              77, 88, 90, 45};
        
              // Simply getting the index value
              Console.WriteLine("Values of the specified index:");
              Console.WriteLine(myarr[0]);
        
              // Now we use index from end(^)
              // operator with the given index
              // This will return the end value
              // which is related to the specified
              // index
              Console.WriteLine("The end values of the specified index:");
              Console.WriteLine(myarr[^0]);
          }
      }
      }

      
      

      Output:

      Values of the specified index:
      34
      The end values of the specified index:
      Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
      at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22

    • You are allowed to use the index as a variable and this variable place in between brackets[]. As shown in the below example:

      Example:




      // C# program to illustrate how
      // to declare a index as a variable
      using System;
         
      namespace example {
         
      class GFG {
         
          // Main Method
          static void Main(string[] args)
          {
         
              // Creating and initializing an array
              int[] number = new int[] {1, 2, 3, 4,
                                    5, 6, 7, 8, 9};
         
              // Declare an index
              // as a variable
              Index i = ^6;
              var val = number[i];
         
              // Displaying number
              Console.WriteLine("Number: " + val);
          }
      }
      }

      
      

      Output:

      Number: 4
  • .. Operator: It is known as the range operator. And it specifies the start and end as its operands of the given range. It is the most compact and easiest way to find the range of the elements from the specified sequence or collection in comparison to earlier methods.
    // Old Method
    var arr = myemp.GetRange(1, 5);
    
    // New Method
    var arr = myemp[2..3]
    

    Example:




    // C# program to illustrate the 
    // use of the range operator(..)
    using System;
       
    namespace example {
       
    class GFG {
       
        // Main Method
        static void Main(string[] args)
        {
            // Creating and initializing an array
            string[] myemp = new string[] {"Anu", "Priya", "Rohit"
                        "Amit", "Shreya", "Rinu", "Sumit", "Zoya"};
       
            Console.Write("Name of the employees in project A: ");
            var P_A = myemp[0..3];
            foreach(var emp1 in P_A)
                Console.Write($" [{emp1}]");
       
            Console.Write("\nName of the employees in project B: ");
            var P_B = myemp[3..5];
            foreach(var emp2 in P_B)
                Console.Write($" [{emp2}]");
       
            Console.Write("\nName of the employees in project C: ");
                var P_C = myemp[1..^2];
                foreach (var emp3 in P_C)
                    Console.Write($" [{emp3}]");
       
            Console.Write("\nName of the employees in project D: ");
            var P_D = myemp[..];
            foreach(var emp4 in P_D)
                Console.Write($" [{emp4}]");
       
            Console.Write("\nName of the employees in project E: ");
            var P_E = myemp[..2];
            foreach(var emp5 in P_E)
                Console.Write($" [{emp5}]");
       
            Console.Write("\nName of the employees in project F: ");
            var P_F = myemp[6..];
            foreach(var emp6 in P_F)
                Console.Write($" [{emp6}]");
       
            Console.Write("\nName of the employees in project G: ");
            var P_G = myemp[^3.. ^ 1];
            foreach(var emp7 in P_G)
                Console.Write($" [{emp7}]");
        }
    }
    }

    
    

    Output:

    Name of the employees in project A:  [Anu] [Priya] [Rohit]
    Name of the employees in project B:  [Amit] [Shreya]
    Name of the employees in project C:  [Priya] [Rohit] [Amit] [Shreya] [Rinu]
    Name of the employees in project D:  [Anu] [Priya] [Rohit] [Amit] [Shreya] [Rinu] [Sumit] [Zoya]
    Name of the employees in project E:  [Anu] [Priya]
    Name of the employees in project F:  [Sumit] [Zoya]
    Name of the employees in project G:  [Rinu] [Sumit]
    

    Important Points:

    • When you create a range using range operator, then it will not add the last 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.
    • In Range, if a range contains starting and ending index like Range[start, end], then such types of ranges are known as the bounded range.
    • In Range, if a range contains only starting, ending index or doesn’t contain starting and ending indexes like Range[start..], or Range[..end], or Range[..], then such types of ranges are known as the unbounded range.
    • You are allowed to use range as a variable and this variable place in between brackets[]. As shown in the below example:

      Example:




      // C# program to illustrate how to
      // declare a range as a variable
      using System;
         
      namespace example {
         
      class GFG {
         
          // Main Method
          static void Main(string[] args)
          {
         
              // Creating and initializing an array
              int[] number = new int[] {1, 2, 3, 4,
                                    5, 6, 7, 8, 9};
         
              Console.Write("Number: ");
         
              // Declaring a range as a variable
              Range num = 1..3;
              int[] val = number[num];
         
              // Displaying number
              foreach(var n in val)
                  Console.Write($" [{n}]");
          }
      }
      }

      
      

      Output:

      Number:  [2] [3]
      


Similar Reads

LINQ | Generation Operator | Empty, Range, and Repeat
The generation operators are used for creating a new sequence of values. The Standard Query Operator supports 4 different types of generation operators: DefaultIfEmpty Empty Range Repeat Empty Operator The Empty operator is used to return an empty collection. Or in other words, we can say that it returns an empty IEnumerable<T> which contain
3 min read
Range Constructor in C#
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 },
2 min read
C# | Remove a range of elements from the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveRange(Int32, Int32) method is used to remove a range of elements from the ArrayList. Properties of the ArrayL
3 min read
C# | Reverse the order of the elements in the entire ArrayList or in the specified range
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Reverse Method is used to reverse the order of the elements in the ArrayList in the specified range. There are two
4 min read
C# | Removing a range of elements from the List
List<T>.RemoveRange(Int32, Int32) Method is used to remove a range of elements from the List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can accept null as a valid value for reference types and it also allows duplicate elements.If the Count becomes equals to Cap
3 min read
C# | Reverse the order of the elements in the entire List or in the specified range
List<T>.Reverse Method is used to reverse the order of the elements in the List<T> or a portion of it. There are two methods in the overload list of List<T>.Reverse Method as follows: Reverse() Reverse(Int32, Int32) Reverse() Method This method is used to reverse the order of the elements in the entire List<T>. Syntax: publi
4 min read
C# | Copy the elements of collection over a range of elements in ArrayList
ArrayList.SetRange(Int32, ICollection) Method is used to copy the elements of a collection over a range of elements in the ArrayList. Syntax: public virtual void SetRange (int index, System.Collections.ICollection c); Parameters: index: It is a zero-based ArrayList index at which to start copying the elements of c. The type of this parameter is Sys
3 min read
C# | Getting an enumerator for a range of elements in the ArrayList
ArrayList.GetEnumerator(Int32, Int32) method is used to get an enumerator for a range of elements in the ArrayList. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (int index, int count); Parameters: index: It is the zero-based starting index of type Int32 of the ArrayList section that the enumerator should refer to. count: It i
3 min read
Getting the Hash Code of the Specified Range 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 get the hash code of the specified range with the help of the GetHashCode() Method provided by the Range struct. This method returns the hash code of the specified instance. Syntax: public override int GetHashCode(); Example 1: //
2 min read
Finding all the Elements of a Range from Start to 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 find all the range object starting from the start index to end with the help of All Property provided by the Range struct. This property always returns 0..^0 range.Syntax: public static property Range All { Range get(); }; Here, R
2 min read
Article Tags :