Arunachalam Arunachalam - 10 days ago 6x
C# Question

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?


Well, the easiest is to use List<T>:

List<int> list = new List<int>();
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.