17

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?

5 Answers 5

22

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.

Sign up to request clarification or add additional context in comments.

3 Comments

obj.myIntArray = (new List<int> { 1,2 }).ToArray();
Is there no way to use "{1,2,3,4,5}"?
@Xonatron yes, collection initializers have been added over the last 7 years, see lamarant's comment. However, if the values are known at compile time, you can just go straight to an array anyway
19

You mean?

int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };

1 Comment

How is this not the top answer?
8

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);
    }
}

1 Comment

Agreed. I almost never use arrays anymore now that generic lists are just so damned easy to use.
0

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.

Comments

0

You could just use the below line instead of calling a separate function:

using System;

public class Test
{
    static void Main()
    {
        Console.WriteLine("Please enter array size");
        int size = Convert.ToInt32(Console.ReadLine());

        int[] array = new int[size];
        for (int i=0; i < size; i++)
        {
            Console.WriteLine("Please enter element " + i);
            array[i] = Convert.ToInt32(Console.ReadLine());
        }

        Console.WriteLine("Finished:");
        foreach (int i in array)
        {
            Console.WriteLine(i);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.