Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how to create a List<T> with a default count of zero?

Tags:

c#

Rookie question:

I have been experiencing a minor bug in my mvc2 application. I was able to trace it back to this code:

List<Stream2FieldTypes> Stream2FieldTypes = new List<Stream2FieldTypes>();
foreach (var item in stream.Stream2FieldTypes) 
{ 
   Stream2FieldTypes.Add(item); 
}

The problem that I am experiencing is that when I instatiate the new list, it has a count of one. I'm thinking that this is probably due to my using the constructor. So I tried this:

List<Stream2FieldTypes> Stream2FieldTypes;
foreach (var item in stream.Stream2FieldTypes) 
{ 
   Stream2FieldTypes.Add(item); 
}

But, of course this will not compile because of an error on Stream2FieldTypes.Add(item);. Is there a way that I can create a List<Stream2FieldTypes> and make sure that the count is zero?

like image 758
quakkels Avatar asked Dec 10 '25 22:12

quakkels


2 Answers

The problem that I am experiencing is that when I instatiate the new list, it has a length of one

No, that's totally impossible. Your problem is somewhere else and unrelated to the number of elements of a newly instantiated list.

List<Stream2FieldTypes> Stream2FieldTypes = new List<Stream2FieldTypes>();

Stream2FieldTypes.Count will be 0 at this point no matter what you do (assuming of course single threaded sequential access but List<T> is not thread-safe anyways so it's a safe assumption :-)).

like image 155
Darin Dimitrov Avatar answered Dec 12 '25 11:12

Darin Dimitrov


The constructor:

List<Stream2FieldTypes> Stream2FieldTypes = new List<Stream2FieldTypes>(0);

will create a list with a default capacity of zero.

ETA: Though, looking at Reflector, it seems that the static and default constructors also create the list with a default capacity of zero. So your code as it stands should create a list with no elements and no reserved capacity. Should be more performant than the explicit constructor.

like image 25
Jesse C. Slicer Avatar answered Dec 12 '25 12:12

Jesse C. Slicer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!