views:

1417

answers:

3

At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.

Queue<MyData> myDataQueue = new Queue<MyData>();

// Populate the queue here


XmlSerializer mySerializer =
  new XmlSerializer(myDataQueue.GetType());    

StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();
+10  A: 

It would be easier (and more appropriate IMO) to serialize the data from the queue - perhaps in a flat array or List<T>. Since Queue<T> implements IEnumerable<T>, you should be able to use:

List<T> list = new List<T>(queue);
Marc Gravell
You could also use queue.ToList()
chakrit
I'd like to know more about the "more appropriate" comment you made.
CrashCodes
@chakrit - only with .NET 3.5, but yes.
Marc Gravell
This doesn't really help if you serialize a class that contains Queue<T>... Unless you are happy to XmlIgnore the Queue and ensure you have a List<T> field holding a copy of the data... Or are there better ways?
romkyns
A: 

if you want to use the built in serialization you need to play by its rules, which means default ctor, and public get/set properties for the members you want to serialize (and presumably deserialize ) on the data type you want to serialize (MyData)

Asher
+1  A: 

Not all parts of the framework are designed for XML serialization. You'll find that dictionaries also are lacking in the serialization department.

A queue is pretty trivial to implement. You can easily create your own that also implements IList so that it will be serializable.

Will