tags:

views:

11149

answers:

5

How to add new item in existing string array in c#.net. i need to preserve the existing data.

+14  A: 

I would use a List if you need a dynamically sized array:

List<string> ls = new List<string>();
ls.Add("Hello");
Ed Swangren
+1  A: 

I agree with Ed. C# does not make this easy the way VB does with ReDim Preserve. Without a collection, you'll have to copy the array into a larger one.

harpo
Thank God! ReDim is incredibly slow when abused. =)
Ed Swangren
+4  A: 

That could be a solution;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

yapiskan
@Konrad, that will surely preserve the data in the array.
yapiskan
A: 

Arrays in C# are immutable, e.g. string[], int[]. It means you can't resize them. You need to create a brand new array.

Here is the code for Array.Resize:

public static void Resize<T>(ref T[] array, int newSize)
{
    if (newSize < 0)
    {
        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    T[] sourceArray = array;
    if (sourceArray == null)
    {
        array = new T[newSize];
    }
    else if (sourceArray.Length != newSize)
    {
        T[] destinationArray = new T[newSize];
        Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
        array = destinationArray;
    }
}

As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the ref keyword for the first parameter.

There are lists that can dynamically allocate new slots for new items. This is e.g. List<T>. These contain immutable arrays and resize them when needed (List<T> is not a linked list implementation!). ArrayList is the same thing without Generics (with Object array).

LinkedList<T> is a real linked list implementation. Unfortunately you can add just LinkListNode<T> emenets to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.

artur02
A: 
private static string[] GetMergedArray(string[] originalArray, string[] newArray)
    {
        int startIndexForNewArray = originalArray.Length;
        Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);
        newArray.CopyTo(originalArray, startIndexForNewArray);
        return originalArray;
    }
Dave Blake