ReDim for C#, using Generics

As an exercise in using Generics, I wrote a ReDim function that works in C#.

Bugs, feedback, criticism, welcome and appreciated.

/// <summary>

/// Redimensions the length of array down(or up) to equal "length" (parameter)

/// This is based on the VB "redim" function, and like that one it does

/// cause a memory overhead and a performance hit. So please use this one

/// sparingly. For example, don't call it in a loop.

/// (Hint: prefer List<T> with it's .Add() method, for frequently redim'd lists)

/// </summary>

/// <typeparam name="T">The Type of Array to be re-dimmed</typeparam>

/// <param name="arr">The array to be re-dimmed</param>

/// <param name="length">The new length of the array</param>

private void ReDim<T>(ref T[] arr, int length)

{

    T[] arrTemp = new T[length];

    if (length > arr.Length) {

        Array.Copy(arr, 0, arrTemp, 0, arr.Length);

        arr = arrTemp;

    } else {

        Array.Copy(arr, 0, arrTemp, 0, length);

        arr = arrTemp;

    }

}

 

My book "Choose Your First Product" is available now.

It gives you 4 easy steps to find and validate a humble product idea.

Learn more.

(By the way, I read every comment and often respond.)

Your comment, please?

Your Name
Your Url (optional)
Note: I may edit, reuse or delete your comment. Don't be mean.