Cassandra B Cassandra B - 2 months ago 12
C# Question

How to add elements to an array in c#?

How can this method add items to an array in C# ?

class Set
{
int [] arr = {1,2,5,4};
int [] arr2 = {3,2,4,8};

public void AddElement()
{
arr.add(90);
}
}

Answer

Arrays are fixed size. If you want to add element to array, you need to create a new one, copy values and then store new value.

But in C# there is Collections, for instance List class (it's in System.Collections.Generic).

var list = new List<int>() { 1, 2, 3 };
list.Add(100);

There is solution for arrays.

class Set 
{
    int[] arr = { 1, 2, 5, 4 };
    int[] arr2 = { 3, 2, 4, 8 };

    public void AddElement() 
    {
        var newArray = new int[arr.Length + 1];
        Array.Copy(arr, newArray, arr.Length);
        newArray[newArray.Length - 1] = 90;
        arr = newArray;
    }
}
Comments