-2

First off, I'm fairly new to coding so my apologies if this is very simple, I'm trying to write a program that counts the number of vowels per line from input data and then displays the counts per line. I'm running into an issue when trying to set the initial capacity of the list that will store the total counts, the capacity keeps getting set to zero even though letters.Count = 15. Below is what I have, and thank you for any and all feedback:

var letters = new List<string>();
        var vowels = new char[] { 'a', 'e', 'i', 'o', 'u'};
        string input;
        while (!String.IsNullOrWhiteSpace(input = Console.ReadLine()))
        {
            letters.Add(input);
            if (letters.Count == input.Length)
                break;
        }

        var length = letters.Count;
        var total = new List<int>(length);
  • _"the capacity keeps getting set to zero"_ -- no, it doesn't. It gets set to `length`, just like your code says to. The problem is that you didn't bother to read the documentation, which specifically says [_"Capacity is the number of elements that the List can store before resizing is required, whereas Count is the number of elements that are actually in the List."_](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.capacity?view=net-5.0#remarks). See duplicate for how to set the actual _count of elements_ in the list. – Peter Duniho Feb 12 '21 at 00:10
  • Use an array if you want to specify the total size ahead of time. Lists were built to get around that limitation by internally resizing an array as needed. The Capacity property just sets the initial size to avoid a lot of resizing during list population. – Rufus L Feb 12 '21 at 00:40

1 Answers1

0
var total = new List<int>(length);

doesn't allocate a list of size length, it just reserves space for it, the list will still be empty.

as per docs https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-5.0#System_Collections_Generic_List_1__ctor_System_Int32_

you could add items to the list, but in this case a better choice is to use an array as it is designed to be initialized to a fixed size.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156