c# - Why "Index was out of range" exception for List<T> but not for arrays? -


when initialize array , access elements using indexer, works fine:

object[] temp = new object[5]; temp[0] = "bar"; 

now expect same work list<t>, given can initialize passing capacity constructor:

list<object> temp = new list<object>(5); temp[0] = "bar"; 

this last line throws following exception:

index out of range. must non-negative , less size of collection

why happen list<t> type, not array? since arrays lower level abstractions collections clr, why exception occur?


original question awais mahmood.

short answer: because 5 different things.

long answer:

when initializing array, set size, , size fixed. array cannot grow or shrink later on. therefore,

object[] temp = new object[5]; 

means create new array 5 elements. hence, can access these elements right after creating array.

for lists, size variable. instances of list<t> class internally use array storing items, , when add or remove items in list, array gets replaced bigger or smaller array. on each of these occasions, items remain in list copied previous array new one. quite costly operation, internal array has overhead of unused items. long items added list , size of internal array not exceeded, array not need replaced.

the 5 pass constructor of list initial size of internal array:

list<object> temp = new list<object>(5); 

that means, list create has zero elements (hence exception), internal array initialized size of 5, can add 5 elements without requiring internal array replaced.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -