C# | Finding the index of last element in the array

GetUpperBound() Method is used to find the index of the last element of the specified dimension in the array.

Syntax:

public int GetUpperBound (int dimension);

Here, dimension is a zero-based dimension of the array whose upper bound needs to be determined.



Return Value:The return type of this method is System.Int32. This method returns the index of the last element of the specified dimension in the array Or -1 if the specified dimension is empty.

Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank.

Note: GetUpperBound(0) returns the last index in the first dimension of the array, and GetUpperBound(Rank – 1) returns the last index of the last dimension of the array. This method is an O(1) operation.

Below programs illustrate the use of GetUpperBound() Method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the GetUpperBound(Int32)
// method in 1-D array
using System;
  
public class GFG {
      
    // Main method
    static public void Main()
    {
  
        // 1-D Array
        int[] value = {1, 2, 3, 4, 5, 6, 7};
  
        // Get the index of the last element
        // in the given Array by using 
        // GetUpperBound(Int32) method
        int myvalue = value.GetUpperBound(0);
          
        Console.WriteLine("Index: {0}", myvalue);
    }
}

chevron_right


Output:

Index: 6

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find last index 
// value and rank of 2-D array
using System;
  
public class GFG {
      
    // Main method
    static public void Main()
    {
  
        // 2-D char Array
        char[, ] value = { { 'a', 'b' }, { 'c', 'd' }, 
                           { 'e', 'f' }, { 'g', 'h' },
                                       { 'i', 'j' } };
  
        // Get the index of the last element
        // and the rank of the given Array
        int myvalue = value.GetUpperBound(0);
        Console.WriteLine("Dimension: {0}", value.Rank);
        Console.WriteLine("Index: {0}", myvalue);
    }
}

chevron_right


Output:

Dimension: 2
Index: 4

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=netcore-2.1



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.