0

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
INDIA IT TECH
  • 1,902
  • 4
  • 12
  • 25
alexcons
  • 531
  • 3
  • 8
  • 18
  • 2
    it should be smaller than the length, not smaller or equal (as the length would be 2 but the last index available is 1 (0, 1 = 2 items) – Icepickle Apr 04 '16 at 11:16
  • 1
    Possible duplicate of [What is IndexOutOfRangeException and how do I fix it?](http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it) – Phiter Apr 04 '16 at 11:17
  • 2
    You should use `KeyValuePair[]` instead. – M.kazem Akhgary Apr 04 '16 at 11:17

3 Answers3

2

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

Change <= to < in the for statement.

navigator
  • 1,678
  • 16
  • 29
0

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++)

Nelson Almendra
  • 784
  • 1
  • 9
  • 20
0

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));
       }