DEV Community

Samiur
Samiur

Posted on • Edited on

How to add items into an Array in C#

By the definition, an array is stored at contiguous memory locations in order that initially it size is fixed. Actually array identifier holds only the reference of memory location and access of elements using index is performed by the following mathematical formula:

location of arr[i] = location of arr[0] + i * size of each element.
Consider we've an array of integer(Int32) arr with length of 5, in order that it have contiguous 5 integers valued allocated memory reference. Since every integer needs 4 bytes, so total referenced size of allocation is bounded in 20 bytes. Let first allocated location is 2020441248 and last allocated location is 2020441229. If we used 0 based indexes, then if we attempt to access arr[5] or quite index of 5 the reference failed to access because arr[5] requires next contiguous 4 bytes [2020441228 to 2020441225] from memory allocation but the identifier isn't conscious of these locations. In order that if we try access any index which is bigger than the array length, then it'll throw an IndexOutOfRangeException runtime exception with a default message like this, "index was outside the bounds of the array”.

How to add items into an Array
In C#, It is not possible to change the array size once is created. So that make sure that your it doesn't have possibility of attempt to access any index of outside than bounded length.

using System;
namespace MainConsole
{
class Program
{
static void Main()
{
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
}

}
Enter fullscreen mode Exit fullscreen mode

}

Alternatively, you can usese List or any of other revalant data structure from System.Collection.Generic namespace so that we can apply methods and change the length of collection dynamically like push(), pop() or add(), remove() etc.

using System;
namespace MainConsole
{
class Program
{
static void Main()
{
List termsList = new List();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}

       // It is possible to convert it back into an array
       int[] terms = termsList.ToArray();
    }

}
Enter fullscreen mode Exit fullscreen mode

}

Click to see more

Top comments (0)