ILearnable .Net

December 10, 2005

Christmas Calendar 10/24

Filed under: Uncategorized — andreakn @ 04:54

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
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 🙂


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: