Saturday, December 10, 2005

Christmas Calendar 10/24

Array casting.

I have stumped on this one in the past:
Why can't I cast an array of one type to an array of another type?.

I fill my ArrayList with nothing but strings, I need to pass the content as a simple string-array (maybe in conjuncture with some web-service).

I call the ToArray(typeof(string)) on the arrayList and we should be done....

.. almost anyway, I also have to typecast the Array returned into the string[]

string[] stringArray = (string[])stringList.ToArray(typeof(string));

ok, this works.. but what if my strings are already contained in a object array, such as would be returned from a call to the simple ToArray() function on ArrayList.

would this work?

object[] object_array = stringList.ToArray();
string[] string_array = (string[]) object_array;

sounds simple? well it is, .. it is too simple, so simple, in fact, that it won't work. You can't bulk-cast an array and all of its content in one go.

(but wait, didn't we just do that above? .... no we didn't. The content was already cast into the correct form. That's how come even though we supplied the object type we still only got a generic Array back the generic Arrays content was correct. only the shell was needed to be explicitly cast into the correct form)

so. what to do eh?
do we have to settle for the old an known?

for(int i = 0; i<object_array.Length; i++)
{
string[i] = (string)object[i];
}


not bloody likely! Let's instead use the Array.CopyTo() function!

string[] string_array = new string[object_array.Length];
object_array.CopyTo(string_array, 0);

so there's two ways of array-cast
Merry xmas to everyone :)

No comments: