In case you really have to Append one array to another

Here is another problem i’ve seen people solve once too many: Append one array to another. STOP. Revisit the problem. Can’t you simply use List<T> and move on to solving actual business problems? In case you really can’t get rid of the arrays read the following:

Given()
{
 source = new[] { SourceElement };
 destination = new[] { DestinationElement };
}

When()
{
 source.AppendTo(ref destination);
}

ThenTheDestinationShouldStillHaveTheDestinationElement()
{
 Assert.AreEqual(DestinationElement, destination[0]);
}

ThenTheDestinationShouldHaveBeenExtendedWithTheSourceElement()
{
 Assert.AreEqual(SourceElement, destination[1]);
}

And here is the code which satisfies the requirements:

public static class Extensions
{
 public static void AppendTo<T>(this T[] sourceArray, ref T[] destinationArray)
 {
  var sourceLength = sourceArray.Length;
  var destinationLength = destinationArray.Length;
  var extendedLength = destinationLength + sourceLength;
  Array.Resize(ref destinationArray, extendedLength);
  Array.Copy(sourceArray, 0, destinationArray, destinationLength, sourceLength);
 }
}

Perhaps it’s time to start (or does it exist already, cause i can’t find it) an open-source project with extension methods.

This entry was posted on Friday, December 4th, 2009 at 08:46 and is filed under C#, Patterns. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply