Casting

G

Guest

Hi All,

I have a piece of code where by I create an arraylist containing elements of
class type ActivityDetail, one of the routines used is generic and returns an
object array, but I can not cast back to ActivityDetail Array see snipet below

ArrayList arrayl = new ArrayList();
ActivityDetail det = new ActivityDetail();
arrayl.Add(det);
object[] obj = (object[]) arrayl.ToArray(typeof(object));
ActivityDetail[] detarr = (ActivityDetail[])obj;

Yet as all objects inherit object I thought this would be OK and I'm sure I
have done similar in the past. I just get invalid cast - any help or
explaination would be appreciated.

TrinityPete
 
M

Mattias Sjögren

object[] obj = (object[]) arrayl.ToArray(typeof(object));

It should work if you change this to

object[] obj = (object[]) arrayl.ToArray(typeof(ActivityDetail));

Yet as all objects inherit object I thought this would be OK

It's the type of the array itself (object[] vs ActivityDetail[]) that
matters, not what kind of objects that are actually referenced.



Mattias
 
G

Guest

Thanks Mattias,

I was sure I had used similar methodology before and couldn't work out why
it wasn't working as expected in this instance. I now see the
ArrayList.ToArray was using the incorrect class.

The thing that threw me was in the dubugger looking at an element in the
object array still had an underlying Sysyem Type of Activity Detail therefore
I believed the cast was valid.

Thanks for your input.
Pete.

Mattias Sjögren said:
object[] obj = (object[]) arrayl.ToArray(typeof(object));

It should work if you change this to

object[] obj = (object[]) arrayl.ToArray(typeof(ActivityDetail));

Yet as all objects inherit object I thought this would be OK

It's the type of the array itself (object[] vs ActivityDetail[]) that
matters, not what kind of objects that are actually referenced.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top