1

I encountered this error with more complex model, but it's a behavior of the List object:

List<int> numbers= new List<int>();
numbers[0] = 12; //The error occurs here
Console.WriteLine(numbers[0]);

The error is:

Index was out of range. Must be non-negative and less than the size of the collection.

edit

I know about Add() and Insert(), but I'm wondering why this odd error happens.

Mohamed
  • 73
  • 1
  • 12

3 Answers3

2

You are trying to access an index (0) that doesn't exist because you are initializing an empty List. You should call the Add() method.

List<int> numbers= new List<int>();
numbers.Add(12);
Console.WriteLine(numbers[0]);
Dan Wilson
  • 3,937
  • 2
  • 17
  • 27
1

You need to call Add method on List like this:

numbers.Add(12)

If you need to access using index, you need to populate the list, then you can use numbers[0] to retrieve first element.

To initialize a list:

List<int> numbers = new List<int>
{
    12,
    15,
    18
};

Now, numbers[1] will return 15.

abdul
  • 1,562
  • 1
  • 17
  • 22
1

When you create a new List<> object, it does not have any values in it, and therefore no indices.

This is why you are getting an error when trying to access the 0th item in the list (like an IndexOutOfBoundsException if you know Java).

Use the Add method on the list to put a new item in it, instead of trying to set it via the index.

numbers.Add(12)

This method appends the given value to the end of the list, and creates the appropriate index for it.

Farwatch
  • 46
  • 3