Thursday, April 28, 2011

How to assign array values at run time

Consider I have an Array,

int[] i = {1,2,3,4,5};

Here I have assigned values for it. But in my problem I get these values only at runtime. How can I assign them to an array.

For example:

I get the max size of array from user and the values to them now how do I assign them to the array int [].

Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?

From stackoverflow
  • Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".

    You can do it explicitly though, like this:

    using System;
    
    public class Test
    {
        static void Main()
        {
            int size = ReadInt32FromConsole("Please enter array size");
    
            int[] array = new int[size];
            for (int i=0; i < size; i++)
            {
                array[i] = ReadInt32FromConsole("Please enter element " + i);
            }
    
            Console.WriteLine("Finished:");
            foreach (int i in array)
            {
                Console.WriteLine(i);
            }
        }
    
        static int ReadInt32FromConsole(string message)
        {
            Console.Write(message);
            Console.Write(": ");
            string line = Console.ReadLine();
            // Include error checking in real code!
            return int.Parse(line);
        }
    }
    
    Wedge : Agreed. I almost never use arrays anymore now that generic lists are just so damned easy to use.
  • Well, the easiest is to use List<T>:

    List<int> list = new List<int>();
    list.Add(1);
    list.Add(2);
    list.Add(3);
    list.Add(4);
    list.Add(5);
    int[] arr = list.ToArray();
    

    Otherwise, you need to allocate an array of suitable size, and set via the indexer.

    int[] arr = new int[5];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;
    

    This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.

  • If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.

    Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.

    Dead account : same here so I deleted mine

0 comments:

Post a Comment