Why I can't add items to the Generic List with indexer?

Viewed 2023

Here is a strange situation I have seen today:

I have a generic list and I want add items to my list with it's indexer like this:

List<string> myList = new List<string>(10);
myList[0] = "bla bla bla...";

When I try this, I'm getting ArgumentOutOfRangeException

enter image description here

Then I looked at List<T> indexer set method, and here it is:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"),    __DynamicallyInvokable] 
  set
  {
    if ((uint) index >= (uint) this._size)  
      ThrowHelper.ThrowArgumentOutOfRangeException();  //here is exception
    this._items[index] = value;
    ++this._version;
  }

And also looked at Add method:

[__DynamicallyInvokable]
public void Add(T item)
{
  if (this._size == this._items.Length)
    this.EnsureCapacity(this._size + 1);
  this._items[this._size++] = item;
  ++this._version;
}

Now, as I see both methods are using the same way:

// Add() Method
this._items[this._size++] = item; 
// Setter method
this._items[index] = value;

The _items is an array of type T :

private T[] _items;

And in the constructor _items initialized like this:

this._items = new T[capacity]

Now, after all of these I'm curious about why I can't add items into my list with an index
,although I specify list capacity explicitly?

4 Answers
Related