Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign array values at run time

Tags:

c#

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?

like image 531
Arunachalam Avatar asked Apr 07 '09 07:04

Arunachalam


People also ask

How do you assign a value to an array at runtime?

Assigning Values to an Arrayint [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks; When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

How do you assign values to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can values be assigned to the array at the time of declaration?

An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time. // initialize an array at the time of declaration.

How do you set the size of an array in Java?

No, we cannot change array size in java after defining. Note: The only way to change the array size is to create a new array and then populate or copy the values of existing array into new array or we can use ArrayList instead of array.


1 Answers

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.

like image 145
Marc Gravell Avatar answered Oct 05 '22 12:10

Marc Gravell