Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Last active September 20, 2018 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjs3339/74285a69f7cbee3b29f6e6f3c0705211 to your computer and use it in GitHub Desktop.
Save mjs3339/74285a69f7cbee3b29f6e6f3c0705211 to your computer and use it in GitHub Desktop.
C# ResizeEx, Resizes Either a Onedimensional or Multidimensional Array to a Specified New Size.
public class ResizeEx
{
/// <summary>
/// Resizes a one-dimensional array to the specified new size.
/// </summary>
public static void Resize<T>(ref T[] array, int newSize)
{
if(newSize <= 0)
throw new ArgumentOutOfRangeException($@"New Size {newSize} must be greater than 0.");
if(array == null)
{
array = new T[newSize];
}
else
{
if(array.Length == newSize)
return;
var tArray = new T[newSize];
Array.Copy(array, 0, tArray, 0, array.Length);
array = tArray;
}
}
/// <summary>
/// Resizes a multidimensional array to the specified new size.
/// </summary>
public static void Resize2D<T>(ref T[,] array, int nX, int nY)
{
if(nX <= 0 || nY <= 0)
throw new ArgumentOutOfRangeException($@"New Size of Columns:{nX} and Rows:{nY} must be greater than 0.");
if(array == null)
{
array = new T[nX, nY];
}
else
{
var newArray = new T[nX, nY];
var mX = Math.Min(array.GetLength(0), newArray.GetLength(0));
var mY = Math.Min(array.GetLength(1), newArray.GetLength(1));
for(var i = 0; i < mX; ++i)
Array.Copy(array, i * mY, newArray, i * nY, mY);
array = newArray;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment