Search code examples
c#indexoutofboundsexception

Why does this code throw an IndexOutOfBounds error?


When trying to split a list in half, using the GetRange function in C#. When running the below code;

Console.WriteLine(cardDeck.Count());
List<card> cardDeckDuplicate = cardDeck.GetRange(0, 26);
Console.WriteLine(cardDeckDuplicate.Count());
List<card> cardDeckDuplicate2 = cardDeck.GetRange(27, cardDeck.Count - 1);
Console.WriteLine(cardDeckDuplicate2.Count());

The list I am trying to split is cardDeck, and card is a user-created object. The output to this program is 52, 26. Then it throws an out of bounds error. Can anyone suggest why? It would be appreciated.


Solution

  • The IndexOutOfBounds exception is thrown when an index of some sort is out of range. In your code, the problem shoud be at the 4th line, where instead of GetRange(27, cardDeck.Count - 1) you should probably write GetRange(27, cardDeckCount - 27) instead!