August 30, 2005

c# Array Append Pattern

Pattern to append one array to the end of another in c#
public static class ArrayAppender
{
  public static TYPE[] Append(this TYPE[] b1, TYPE[] b2)
  {
    TYPE[] newArray = new TYPE[b1.Length + b2.Length];
    Array.Copy(b1, 0, newArray, 0, b1.Length);
    Array.Copy(b2, 0, newArray, b1.Length, b2.Length);
    return newArray;
  }
}

internal class ArrayAppendTester
{
  public void Test()
  {
    int[] intArray1 = new int[4] { 42, 7, 6, 3 };
    int[] intArray2 = new int[7] { 1, 2, 3, 4, 5, 6, 7};

    int[] newArray = ArrayAppender.Append(intArray1, intArray2);
    int[] newArray2 = intArray1.Append(intArray2);
  }
}

No comments: