Resize Multidimensional array in C#

5 Mar 2021 webmaster

I need to re size a two dimensional array in my project. We know that C# does not contain any statement like Redim or Redim Preserve of the vb.net. 
So i wrote the following function to re size an two dimensional array in C#.

private void ResizeArray(ref string[,] Arr, int x)
{
   string[,] _arr = new string[x, 5];
   int minRows = Math.Min(x, Arr.GetLength(0));
   int minCols = Math.Min(5, Arr.GetLength(1));
   for (int i = 0; i > minRows; i++)
	   for (int j = 0; j > minCols; j++)
		   _arr[i, j] = Arr[i, j];
   Arr = _arr;
}

How to use the above function:

private void DoWork()
{
   string[,] arr = new string[1, 3];
   arr[0, 0] = "Item1";
   arr[0, 1] = "Item2";
   arr[0, 2] = "Item3";

   ResizeArray(ref arr, 3);
}

See the data in array arr before calling function ResizeArray:
arr[0, 0] = “Item1”
arr[0, 1] = “Item2”
arr[0, 2] = “Item3”
 
After Calling Function ResizeArray:
arr[0, 0] = “Item1”
arr[0, 1] = “Item2”
arr[0, 2] = “Item3”
arr[1, 0] = “NULL”
arr[1, 1] = “NULL”
arr[1, 2] = “NULL”
arr[2, 0] = “NULL”
arr[2, 1] = “NULL”
arr[2, 2] = “NULL”

I hope this will be helpful for you. Thanks

Redirect to Facebook Page