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.
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
{
#region Static Methods
// |===========================================================================================================|
// | CastArray
// |===========================================================================================================|
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;
}
// |===========================================================================================================|
// | CastArray
// |===========================================================================================================|
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;
}
#endregion Static Methods
}
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<Point>(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<Point>(objectArray);
As you can see its a very simple solution that will work for all your array casting needs.
Great post!
Comment by flashplayer — July 7, 2009 @ 3:34 pm