AndrewGreaves

I am using an ArrayList (stuck in 1.1 land) to build an array dynamical, but because it needs to be serialized (and therefore typed) I am converting the completed ArrayList to a typed Array[].

Here is code that works:

enrollment[] manifest_final = (enrollment[])manifest.ToArray();

And here is code that give an Invalike Cast error:

(enrollment)manifest[ i ]).lectures = (eLecture[])((enrollment)manifest[ i ]).tempLecs.ToArray();

The second line deals with an arraylist 'tempLecs' inside each enrollment object. I don't know if that scope is part of the problem.

Does anyone have any ideas

Thanks in advanced!

Andrew


Re: Visual C# Language Cast Problem with ArrayList.ToArray()

AndrewGreaves

Update:

//create typed arrays out of ArrayLists
for(int i = 0;i < manifest.Count;i++)
{
ArrayList tLects = ((enrollment)manifestIdea).tempLecs;
eLecture[] tLectsArr = (eLecture[])tLects.ToArray();
((enrollment)manifestIdea).lectures = tLectsArr;
}
enrollment[] manifest_final = (enrollment[])manifest.ToArray();

This gives the same error on:

eLecture[] tLectsArr = (eLecture[])tLects.ToArray();








Re: Visual C# Language Cast Problem with ArrayList.ToArray()

JJ Jordan - MSFT

Hi Andrew,

The invalid cast error stems from the fact that ArrayList.ToArray() returns a standard Object array instead of any typed array.  There is no way to simply cast object[] to eLecture[], even if all of the items in the array are eLecture's!  If you could, then you could have some nasty things happening, e.g.:

object[] objArray = new object[] {"1", "2", "3"};
string[] strArray = (string[]) objArray; // Suppose this were legal.
// Note strArray == objArray (point to same array object)

objArray[0] = 1; // Then this is legal too
Debug.Assert(strArray[0] is string); // Should be true, but isn't!

You mentioned in your first message that the last line (enrollment[] manifest_final...) is working, but I'll bet it isn't, by the same rule.  The proper way to create a typed array from an ArrayList is to do something like the following:

enrollment[] manifest_final = new enrollment[manifest.Count];
manifest.CopyTo(manifest_final);

Hope this helps,

JJ






Re: Visual C# Language Cast Problem with ArrayList.ToArray()

Mark Dawson

Hi,

do you have the exact error message from the exception

Mark.