Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy I can't add items to the Generic List with indexer?
    primarykey
    data
    text
    <p>Here is a strange situation I have seen today:</p> <p>I have a generic list and I want add items to my list with it's indexer like this:</p> <pre><code>List&lt;string&gt; myList = new List&lt;string&gt;(10); myList[0] = "bla bla bla..."; </code></pre> <p>When I try this, I'm getting <code>ArgumentOutOfRangeException</code></p> <p><img src="https://i.stack.imgur.com/Mkzf5.png" alt="enter image description here"></p> <p>Then I looked at <code>List&lt;T&gt;</code> indexer set method, and here it is:</p> <pre><code>[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] set { if ((uint) index &gt;= (uint) this._size) ThrowHelper.ThrowArgumentOutOfRangeException(); //here is exception this._items[index] = value; ++this._version; } </code></pre> <p>And also looked at <code>Add</code> method:</p> <pre><code>[__DynamicallyInvokable] public void Add(T item) { if (this._size == this._items.Length) this.EnsureCapacity(this._size + 1); this._items[this._size++] = item; ++this._version; } </code></pre> <p>Now, as I see both methods are using the same way:</p> <pre><code>// Add() Method this._items[this._size++] = item; // Setter method this._items[index] = value; </code></pre> <p>The <code>_items</code> is an array of type <code>T</code> :</p> <pre><code>private T[] _items; </code></pre> <p>And in the constructor <code>_items</code> initialized like this:</p> <pre><code>this._items = new T[capacity] </code></pre> <p>Now, after all of these I'm curious about why I can't add items into my list with an index<br> ,although I specify list capacity explicitly? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload