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?
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 :-)).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With