Jeremy's Blog

ArrayShift in C#

by Jeremy on Sep.29, 2009, under Journey of Souls

This probably isn’t the most elegant or efficient method of doing this, but I needed a way to perform an “ArrayShift” on an array in C#. There’s no built-in method to do this, so I wrote up and dropped this method in my ToolBox:

/// <summary>
/// A C# implementation of "ArrayShift" this is a generic method that
/// will take an Array of T's, shift one off of the beginning of the
/// array and return it.
/// </summary>
/// <typeparam name="T">The type of array.</typeparam>
/// <param name="array">An array of T's, will be modified to remove
/// the first element.</param>
/// <returns>First element of array.</returns>
public static T ArrayShift<T>(ref T[] array)
{
   T first = array[0];
   IList<T> list = array.ToList();
   list.RemoveAt(0);
   array = list.ToArray();

   return first;
}

It’s a quick and dirty way to accomplish what I needed. If anyone has a better method, I’m open to it.

:, ,

2 comments for this entry:

  • Steven

    Isn’t there a C# keyword that lets you use pointers in your class/method?

    Like,

    public static T ArrayShift(T *array)
    {
    T first = array[0];
    T[] newArray = new T[ array.Length - 1 ];
    memcpy((void *) newArray, (const void *) (array + 1), sizeof(T) * (array.Length – 1));

    // free memory, then reassign it to the new array.
    delete[] array;
    array = newArray;

    return first;
    }

    Something like “array++;” sounds easier, but I’m not sure if it would update the indexes/Length property.

  • Steven

    Mentioned this over AIM, but I’ll repost for everyone. Looks less ugly and doesn’t require “unsafe” code.

    public static T ArrayShift(ref T[] array)
    {
    T first = array[0];
    // (src, srcStartIndex, dest, destStartIndex, itemsToCopy)
    System.Array.Copy(array, 1, array, 0, array.Length – 1);
    return first;
    }

    I’m sure System.Array.Copy handles the pointers and memcpy/memmove internally.

Trackbacks / Pingbacks

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!