开发者

How do I create a dynamically sized array, or re-size an array in c#?

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("Pl开发者_开发知识库ease 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;

    }


You could use a List<int> during your method logic and then return myIntList.ToArray();


Typically for this type of application you'll want to use a List. And if you really need an array you can use the ToArray method but reconsider if an array is really what you want. Usually a List is used for a dynamically sized collection instead of an array.

You could always modify your code as follows:

static int[] fillArray()
{
    List<int> list = new List<int>();

    do
    {
        Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
        string consoleInput = Console.ReadLine();

        if (consoleInput == "x")
        {
            return list.ToArray();
        }
        else
        {
            list.Add(Convert.ToInt32(consoleInput));
        }

    } while (count < 8);

    return list.ToArray();
}

But as I mentioned before, really reconsider changing your method to return a List and use the List in your calling code.


Well you could implement your own method accepting the array and new size as parameters that would create new array, deep-copy the elements and then assign to your array. Array.Resize() does the same, you can watch it with disassembler

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜