Problem
I’ve found myself in the situation where I have an array of objects that I want to cast into an array of some other type. You’d think that this would be as simple as: (TheType[])objectArray, but unfortunately, one way or another, you have to loop through each object and cast it into the new type. This becomes a pain when you need to do it frequently.
Solution
There are several ways to write this bit of code, as you can see here , but I decided on using a simple for loop and generics; This way I don’t have to import any namespaces and since I’m using generics I don’t have to write this code ever again. The code is below:
public static class ArrayCastingHelper { public static T[] CastArray<T>(object array) { int totalItems = ((object[])array).Length; T[] castedItems = new T[totalItems]; for (int index = 0; index < totalItems; index++) { castedItems[index] = (T)((object[])array)[index]; } return castedItems; } public static T[] CastArray<T>(object[] array) { int totalItems = array.Length; T[] castedItems = new T[totalItems]; for (int index = 0; index < totalItems; index++) { castedItems[index] = (T)array[index]; } return castedItems; } }
Here is an example of how the class is used:
// Create an array of objects, that are really Points. object[] objectArray = new object[] { new Point(0,0), new Point(1,1), new Point(2,2) }; // This code would throw an InvalidCastException at run-time. //Point[] pointArray = (Point[])objectArray; // Instead we will use the helper class. Point[] pointArray = ArrayCastingHelper.CastArray(objectArray);
Here’s an example of using the other method on the ArrayCastingHelper class:
// Create a single object that is really an array of objects, that are really Points. object objectArray = new object[] { new Point(0,0), new Point(1,1), new Point(2,2) }; // This code would throw an InvalidCastException at run-time. //Point[] pointArray = (Point[])objectArray; // Instead we will use the helper class. Point[] pointArray = ArrayCastingHelper.CastArray(objectArray);
As you can see its a very simple solution that will work for all your array casting needs.
Updated Solution (C# 3.5 or later)
The solution I posted above uses pre-C# 3.5 techniques, however it still works just fine in later versions. With the introduction of C# 3.5 and LINQ we can now simplify this task quite a bit. However not everyone likes using LINQ so the choice is up to you. In addition, note that your project must reference the LINQ library (“System.Linq”) and you must provide a using statement for the LINQ namespace (“System.Linq”).
using System.Linq; // Create an array of objects, that are really Points. object[] objectArray = new object[] { new Point(0,0), new Point(1,1), new Point(2,2) }; // This code would throw an InvalidCastException at run-time. //Point[] pointArray = (Point[])objectArray; // Instead we will use LINQ. Point[] pointArray = objectArray.Cast().ToArray();
#1 by flashplayer on July 7, 2009 - 3:34 pm
Great post!