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;

    }

}

 

I'm currently writing a book about how to build your first product. If you want to build your first product, please sign up to be notified when the book is available.

(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.