alexcons
alexcons

Reputation: 531

I do not know why I am getting a System.IndexOutOfRangeException? C#

I have the following code:

public static KeyValuePair<string[], string[]> GetAccounts()
{   
    string[] usernames = { "user1", "user2", "user3" };
    string[] oauths = { "oauth1", "oauth2", "oauth3" };
    return new KeyValuePair<string[], string[]> (usernames, oauths);
}

And then I am calling the function in Main():

public static void Main(string[] args)
{
    KeyValuePair<string[], string[]> users = GetAccounts ();
    for (int i = 0; i <= users.Key.Length; i++) {
        Console.WriteLine (i);
        Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
   }

}

However, when I get a System.IndexOutOfRangeException on the second console write line. I have no idea why this does not work. I am expecting to see:

 user1 oauth1
 user2 oauth2
 user3 oauth3

Upvotes: 0

Views: 202

Answers (3)

Shrutika Kalra
Shrutika Kalra

Reputation: 121

You are getting System.IndexOutOfRangeException because your for loops run 4 times instead of three and in the last loop it searches for users.Key.GetValue(3) which is not present.

You can use below code to rectify

  for (int i = 0; i < users.Key.Length; i++) {
            Console.WriteLine (i);
            Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
       }

or

for (int i = 0; i <= users.Key.Length-1; i++) {
            Console.WriteLine (i);
            Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
       }

Upvotes: 0

Nelson Almendra
Nelson Almendra

Reputation: 881

the variable i cannot be equal to users.Key.Length.

Change for (int i = 0; i <= users.Key.Length; i++) to for (int i = 0; i < users.Key.Length; i++)

Upvotes: 0

navigator
navigator

Reputation: 1708

for (int i = 0; i < users.Key.Length; i++)

Change <= to < in the for statement.

Upvotes: 2

Related Questions