In C#, How can I serialize Queue<>? (.Net 2.0)

11,736

Solution 1

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);

Solution 2

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.

Share:
11,736
Ambuj Mehra
Author by

Ambuj Mehra

I enjoy writing software. I am currently working on Android hybrid apps for retail in store devices as well as some Websphere Commerce.

Updated on June 04, 2022

Comments

  • Ambuj Mehra
    Ambuj Mehra almost 2 years

    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();
    
  • chakrit
    chakrit over 15 years
    You could also use queue.ToList()
  • Ambuj Mehra
    Ambuj Mehra over 15 years
    I'd like to know more about the "more appropriate" comment you made.
  • Marc Gravell
    Marc Gravell over 15 years
    @chakrit - only with .NET 3.5, but yes.
  • Roman Starkov
    Roman Starkov over 14 years
    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?