My users pass me an array of some type, say int[] or string[]. I can easily query the types of the elements via GetElementType, and I can find out how long the array was when i
In case anyone is curious, I ended up switching my code to use List
I agree with the comments that you should be using List(Of T), but if you want to copy your array into a new array of the same type, you could do something like the following.
// Your passed in array.
object[] objs = new object[5] {1,2,3,4,5};
// Create an array of the same type.
Array a = Array.CreateInstance(objs[0].GetType(), objs.Length+3);
// Copy in values.
objs.CopyTo(a,0);
This should work:
static void Resize(ref Array array, int newSize) {
Type elementType = array.GetType().GetElementType();
Array newArray = Array.CreateInstance(elementType, newSize);
Array.Copy(array, newArray, Math.Min(array.Length, newArray.Length));
array = newArray;
}
Why not just create a new array of whichever type you need that is the size that you want? Then populate it from the array you want to resize, setting non existent values to some default.
I guess I'll just switch to using Lists, but this is a shame; the code will be quite a bit messier looking and since my users are basically at the level of first-semester ugrads, each little thing will make their lives less good. But I'm suspecting that you folks don't see a way to do this either. Oh well....