Array.Resize is a pretty cool little tool. Copy hints might be a nice addition?
If you normally use the supporting collections, this won't be much of a toy for you. If you rely on arrays, and lots of them, and find yourself resizing them every now and then with little helper functions or inline resize code, then you should check this out. The Array.Resize will take and expand an array (by appearance in place, but in actuality doing a copy) given a new size. The actual code behind the API looks something like:
public static void Resize<T>(ref T[] source, int newSize) {
if ( source == null ) { source = new T[newSize]; } else if ( source.Length != newSize ) {
T[] dest = T[newSize];
Array.Copy(source, 0, dest, 0, (newSize > source.Length) ? source.Length : newSize);
source = dest;
}
}
Rewrote that little guy so you could see the various tools involved. First, the resize will work on null arrays. That means this is a great tool for late-bound array expansion in custom collections. You don't have to bother making sure the input is valid because this function does that for you. Pretty nice.
The second tool is obviously the normal array copying semantics. Note the optimization of not expanding arrays if the new size and the old size are identical. In a low performance situation this method can actually become your EnsureCapacity function without you even doing pre-checks. You'd expand your capacity on the *previous* operation once you realized you were going over the bounds of the array, and this method would then resize the array to the new size the next time someone adds an item.
The third tool is the LoD tool or Loss of Data tool. This is based on the fact the new array can be smaller than the previous array. This gives you a TrimToSize tool for free, but at the same time sets you up for accidentally deleting your own data by accidentally passing a smaller new capacity than before. That is where I thought the hints would be handy:
public enum ResizeHints {
None=0,
EndCopy=0x1,
GrowOnly=0x2
}
if ( (resizeHint & ResizeHints.GrowOnly) > 0 ) {
if ( newSize < source.Length ) { return; // Do Something here }
}
int length = (newSize > source.Length) ? source.Length : newSize;
if ( (resizeHint & ResizeHints.EndCopy) > 0 ) {
Array.Copy(source, source.Length - length, dest, dest.Length - length, length);
} else {
Array.Copy(source, 0, dest, 0, length);
}
Even with the new hints you don't get much extra mileage out of the API. The growth protection is nice from a debugging standpoint. The EndCopy is mainly for backloaded arrays and stack structures where you are building top-down. You could also use this method to trim the end off of a larger array in a kind of TopN approach.