Adding elements to a C# array

The obvious suggestion would be to use a List<string> instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.

Of course, I want to make things more interesting (my day that is), so I will answer your question directly.

Here are a couple of functions that will Add and Remove elements from a string[]...

string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    for(int i = 0; i < array.Length; i++)
        result[i] = array[i];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }  

    return result;
}

If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0

Don't use an array - use a generic List<T> which allows you to add items dynamically.

If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.

Tags:

C#