ArrayList.ToArray() question

  • Thread starter Thread starter Derrick
  • Start date Start date
D

Derrick

If i have an ArrayList, add a bunch of MyClass classes to it, how do I get a
MyClass[] out of it? I've tried:

MyClass[] clses = ArrayList.ToArray(typeof(MyClass));

but get errors about not being able to cast. ?

Thanks!

Derrick
 
Derrick,

Yes, because the return type of the ToArray method is Array. You have
to cast it to (MyClass[]), like so:

MyClass[] clses = (MyClass[]) ArrayList.ToArray(typeof(MyClass));

Hope this helps.
 
Hi,

You should do this inside a try/catch block as ArrayList do not check that
all the elements being of the same type.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Nicholas Paldino said:
Derrick,

Yes, because the return type of the ToArray method is Array. You have
to cast it to (MyClass[]), like so:

MyClass[] clses = (MyClass[]) ArrayList.ToArray(typeof(MyClass));

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Derrick said:
If i have an ArrayList, add a bunch of MyClass classes to it, how do I
get
a
MyClass[] out of it? I've tried:

MyClass[] clses = ArrayList.ToArray(typeof(MyClass));

but get errors about not being able to cast. ?

Thanks!

Derrick
 
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us> said:
You should do this inside a try/catch block as ArrayList do not check that
all the elements being of the same type.

Yes it does - it *has* to when you provide a type to ToArray, otherwise
it wouldn't be able return an array of the appropriate type. So ToArray
will throw an exception if the elements aren't of an appropriate type.
Or did you mean that it doesn't check the elements when they're put
into the list?

I wouldn't suggest putting it in a try/catch block though - if that
fails, chances are you've got some nasty internal error, and the
exception should probably bubble up to a higher level.
 
Hi ,
Yes it does - it *has* to when you provide a type to ToArray, otherwise
it wouldn't be able return an array of the appropriate type. So ToArray
will throw an exception if the elements aren't of an appropriate type.
Or did you mean that it doesn't check the elements when they're put
into the list?

When they are inserted on the list I meant.
I wouldn't suggest putting it in a try/catch block though - if that
fails, chances are you've got some nasty internal error, and the
exception should probably bubble up to a higher level.

Cheers,
 
Back
Top