I need to know how to dynamically re-size an array in C#. In the method that I have written below, I need to be able to return an array that only contains the numbers that were input by the user up to 8 numbers. So if the user decides they only want to enter 3 numbers, the array should only contain 3 numbers, not 8.
Now I know that an array needs to include a size when instantiated. So how do I get around this without using a list? Is there a way to re-size the array after the loop is done?
Thanks in advance.
static int[] fillArray()
{
int[] myArray;
myArray = new int[8];
int count = 0;
do
{
Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
string consoleInput = Console.ReadLine();
if (consoleInput == "x")
{
Array.Resize(ref myArray, count);
return myArray;
}
else
{
myArray[count] = Convert.ToInt32(consoleInput);
++count;
}
} while (count < 8);
Array.Resize(ref myArray, count);
return myArray;
}