Expand an array to a given size

Some functions expect an array with a minimum size. While this is generally bad coding sometimes you can’t avoid it (e.g. with csv files).

That’s when this piece of code comes in handy: (it’s an extension method, so it only works on .NET 3.5)

public static class ArrayHelper
{
    /// <summary>
    /// Expands an array to the given <paramref name="size"/>
    /// </summary>
    /// <typeparam name="T">The type of the array (not neccesairy, can be infered).</typeparam>
    /// <param name="array">The array</param>
    /// <param name="size">The size it should become</param>
    /// <returns>The array expanded to the given size</returns>
    public static T[] Expand<T>(this T[] array, int size)
    {
        if (size < array.Length)
        {
            throw new ArgumentException("size < array.Length, this will cause data to be truncated, canceling", "size");
        }

        T[] list = new T[size];

        for (int index = 0; index < array.Length; index++)
        {
            list[index] = array[index];
        }

        return list;
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string[] array = new string[] { "test1", "test2", "test3" };

        //array1 has a length of 3
        Console.WriteLine("array.Length = {0}", array.Length); 

        array = array.Expand<string>(10);

        //now array has a length of 10
        Console.WriteLine("array.Length = {0}", array.Length);

        Console.ReadLine();
    }
}

Enjoy :)