Just for fun, here is one way to use generics to redo / expand a one-dimensional array (add another βrowβ):
static T[] Redim<T>(T[] arr, bool preserved) { int arrLength = arr.Length; T[] arrRedimed = new T[arrLength + 1]; if (preserved) { for (int i = 0; i < arrLength; i++) { arrRedimed[i] = arr[i]; } } return arrRedimed; }
And one, to add n lines (although this does not prevent the user from overriding the array, which will cause an error in the for loop):
static T[] Redim<T>(T[] arr, bool preserved, int nbRows) { T[] arrRedimed = new T[nbRows]; if (preserved) { for (int i = 0; i < arr.Length; i++) { arrRedimed[i] = arr[i]; } } return arrRedimed; }
I am sure you understand.
For a multidimensional array (two dimensions), there is one possibility:
static T[,] Redim<T>(T[,] arr, bool preserved) { int Ubound0 = arr.GetUpperBound(0); int Ubound1 = arr.GetUpperBound(1); T[,] arrRedimed = new T[Ubound0 + 1, Ubound1]; if (preserved) { for (int j = 0; j < Ubound1; j++) { for (int i = 0; i < Ubound0; i++) { arrRedimed[i, j] = arr[i, j]; } } } return arrRedimed; }
In your program, use this with or even without the specified type, the compiler will recognize it:
int[] myArr = new int[10]; myArr = Redim<int>(myArr, true);
or
int[] myArr = new int[10]; myArr = Redim(myArr, true);
Not sure if this is all true. = D Feel free to correct me or improve the code .;)
Tete1805 Dec 18 '13 at 18:28 2013-12-18 18:28
source share