Deserialising unable to cast
Hi All,
I have a class that I have put [Serializable] above the constructor.
This class has an Arraylist of other objects of a different class which also has this heading.
I have a form that holds an ArrayList of objects that are the first class.
I can serialise using this:
Code:
FS = new FileStream("C:/pop_queries.dat", FileMode.Create, FileAccess.Write);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(FS, common.ToArray());
FS.Close();
And try to deserialise using this:
Code:
Query[] queriesFromFile;
FS = new FileStream("C:/pop_queries.dat", FileMode.Open, FileAccess.Read);
BinaryFormatter b = new BinaryFormatter();
queriesFromFile = (Query[])b.Deserialize(FS);
FS.Close();
Query is the same type as the items held in the ArrayList common, which I convert array in the serialisation!
When I try to deserialise, I get the error:
Unable to cast object of type 'System.Object[]' to type 'ClassifyGUI.Query[]'.
Can anybody see where I have gone wrong?
Sam
Re: Deserialising unable to cast
Yup... when you serialized it... you serialized it as an array[] object....
common.ToArray() <<< --- right there....
Try just common....
Also... why an ArrayList and not a List<T> ? what version of the FW are you using?
-tg
Re: Deserialising unable to cast
The ArrayList.ToArray method returns an Object[]. If you want a Query[] when you call ToArray then, as tg says, you should be using List<Query> rather than an ArrayList. If that's not possible for some reason, like you're using .NET 1.x, then you will have to manually create a Query[] and copy the elements from the Object[] before serializing.