Prepend to a C# Array

If you are only going to perform this operation once then there isn’t a whole lot of choices. The code provided by Monroe’s answer should do just fine.

byte[] newValues = new byte[values.Length + 1];
newValues[0] = 0x00;                                // set the prepended value
Array.Copy(values, 0, newValues, 1, values.Length); // copy the old values

If, however, you’re going to be performing this operation multiple times you have some more choices. There is a fundamental problem that prepending data to an array isn’t an efficient operation, so you could choose to use an alternate data structure.

A LinkedList can efficiently prepend data, but it’s less efficient in general for most tasks as it involves a lot more memory allocation/deallocation and also looses memory locallity, so it may not be a net win.

A double ended queue (known as a deque) would be a fantastic data structure for you. You can efficiently add to the start or the end, and efficiently access data anywhere in the structure (but you can’t efficiently insert somewhere other than the start or end). The major problem here is that .NET doesn’t provide an implementation of a deque. You’d need to find a 3rd party library with an implementation.

You can also save yourself a lot when copying by keeping track of “data that I need to prepend” (using a List/Queue/etc.) and then waiting to actually prepend the data as long as possible, so that you minimize the creation of new arrays as much as possible, as well as limiting the number of copies of existing elements.

You could also consider whether you could adjust the structure so that you’re adding to the end, rather than the start (even if you know that you’ll need to reverse it later). If you are appending a lot in a short space of time it may be worth storing the data in a List (which can efficiently add to the end) and adding to the end. Depending on your needs, it may even be worth making a class that is a wrapper for a List and that hides the fact that it is reversed. You could make an indexer that maps i to Count-i, etc. so that it appears, from the outside, as though your data is stored normally, even though the internal List actually holds the data backwards.

Leave a Comment