Home > DeveloperSection > Forums > Insert inside list in C#
Takeshi Okada
Takeshi Okada

Total Post:89

Posted on    January-25-2014 1:33 AM

 C# C# 

 1 Reply(s)
 1520  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??

Pravesh Singh

Total Post:412

Posted on    January-25-2014 1:50 AM

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));

Don't want to miss updates? Please click the below button!

Follow MindStick