Open In App

C# | Getting the value at the specified index of a SortedList object

Last Updated : 01 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
SortedList.GetByIndex(Int32) Method is used to get the value at the specified index of a SortedList object. Syntax:
public virtual object GetByIndex (int index);
Here index is the zero-based index of the value to get. Return Value: It returns the value at the specified index of the SortedList object. Exception: This method will throw ArgumentOutOfRangeException if the index is outside the range of valid indexes for the SortedList object. Below programs illustrate the use of above-discussed method: Example 1: CSharp
// C# code to get the value at the specified
// index of a SortedList object.
using System;
using System.Collections;

class Geeks {

    // Main Method
    public static void Main(String[] args)
    {

        // Creating a SortedList of integers
        SortedList mylist = new SortedList();

        // Adding elements to SortedList
        mylist.Add("1", "C++");
        mylist.Add("2", "Java");
        mylist.Add("3", "DSA");
        mylist.Add("4", "Python");
        mylist.Add("5", "C#");

        // getting the indexing and
        // store into a variable
        int i = 4;

        // getting the value at index 4
        Console.WriteLine("Value at index {0} is {1}",
                          i, mylist.GetByIndex(i));
    }
}
Output:
Value at index 4 is C#
Example 2: CSharp
// C# code to get the value at the specified
// index of a SortedList object.
using System;
using System.Collections;

class Geeks {

    // Main Method
    public static void Main(String[] args)
    {

        // Creating a SortedList of integers
        SortedList mylist = new SortedList();

        // Adding elements to SortedList
        mylist.Add("First", "Ram");
        mylist.Add("Second", "Shyam");
        mylist.Add("Third", "Mohit");
        mylist.Add("Fourth", "Rohit");
        mylist.Add("Fifth", "Manish");

        // getting the indexing and
        // store into a variable
        // it will give error as
        // index is out of range
        int i = 7;

        // getting the value at index 7
        Console.WriteLine("Value at index {0} is {1}",
                          i, mylist.GetByIndex(i));
    }
}
Runtime Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Reference:

Next Article

Similar Reads