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

Adding Elements into an Array

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

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


I'm in the need of Assistance with understanding how to add methods to an array in C# .

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