INSERT INSIDE LIST IN C#

Takeshi Okada

Total Post:89

Points:629
Posted by  Takeshi Okada
C# 
C#
 1583  View(s)
Ratings:
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 -

 lFiles.Insert(6,"File.log.6");

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. Pravesh Singh

    Post:412

    Points:2888
    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));

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!