Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an array of an unknown size C# [duplicate]

Tags:

arrays

c#

Possible Duplicate:
Array of an unknown length in C#

I want to create a program where users can input there items and those items will be stored in an array. When the user is okay with the amount of items, the program will ask for every item if he got it.

The problem is i cant seem to create an array that is of unknown size. I tried to use something like this: String[] list = new string[]{}; But when the program goes there it gives an IndexOutOfRangeException.

Is there a way i can do this?

This is the full code:

bool groceryListCheck = true;
        String[] list = new string[]{};
        String item = null;
        String yon = null;
        int itemscount = 0;
        int count = 0;

        while (groceryListCheck)
        {
            Console.WriteLine("What item do you wanna go shop for?");
            item = Console.ReadLine();
            list[count] = item;
            count++;
            Console.WriteLine("Done?");
            yon = Console.ReadLine();
            if (yon == "y")
            {
                groceryListCheck = false;
                itemscount = list.Count();
            }
            else
            {
                groceryListCheck = true;
            }
        }

        for (int x = 0; x < itemscount; x++)
        {
            Console.WriteLine("Did you got the " + list[x] + "?");
            Console.ReadKey();
        }
like image 938
Dallox Avatar asked Jan 30 '13 16:01

Dallox


1 Answers

Use a List instead of an array.

List<string> myList = new List<string>();
myList.Add("my list item");

After you have gathered all of the items, you can then use a foreach loop to iterate through all of the items in the collection.

foreach(string listItem in myList)
{
    Console.WriteLine(listItem);
}
like image 132
Dave Zych Avatar answered Sep 22 '22 14:09

Dave Zych