Advertise with us

Insert inside list in C#

Posted by  Takeshi Okada
 2244  View(s)
Rate this:

I am initializing my list as below -

 List<string> lFiles = new List<string>(12);

and now I want to add/insert my string at specific index.

like I am using below -


it it throwing excepton as - "Index must be within the bounds of the List."

While initializing I have declared capacity of List but still I am not able insert strings at random indexes.

Anybody knows what I am missing??

  1. Re: Insert inside list in C#

    Hi Takeshi,

    You are initializing the capacity of the list (basically setting the initial size of the internal array for performance purposes), but it does not actually add any elements to the list.

    The easiest way to check this is try this:

    var list1 = new List<int>();
    var list2 = new List<int>(12);
    Console.WriteLine(list1.Count);  //output is 0
    Console.WriteLine(list2.Count);  //output is 0

    This shows that you still don't have any elements in your list.

    In order to initialize populate the array with default or blank elements, you need to actually put something into the list.

    int count = 12;
    int value = 0
    List<T> list = new List<T>(count);
    list.AddRange(Enumerable.Repeat(value, count));

      Modified On Apr-04-2018 01:48:30 AM