After serializing/deserializing two Lists, List.Remove won't remove any items
c#, serialization, windows-phone-7
Solution
`XmlSerializer` is a tree serializer; if the same object is found twice in the graph, it will be serialized twice. When deserializing, this is then two separate objects that happen to look alike. Since `Remove` etc uses equality, which defaults to reference-equality, this is probably the issue, i.e. for that object deserialized, the two occurrences are not the same reference any more. Hence not found.
Options:
- except when declaring actual data, only serialize the id/key - not the object; fixup after deserialization
- use a serializer that can support object references (not `XmlSerializer`)
Problem
When my Windows Phone 7 game is tombstoned during gameplay, I serialize the necessary elements so when they come back to the game it can deserialize the saved data and the user can continue where they left off. I have a List of questions (questionList) and a List of board pieces (boardPieces). These both get serialized/deserialized when navigating away from my game and that all seems to work just fine. When you answer a question, that question is removed from the list: ``` questionList.Remove(boardPiece.Question); ``` This works just fine until I tombstone my game and navigate back to it (after the List's are serialized/deserialized). Then my questionList.Remove... fails to works properly. I checked the data through breakpoints and questionList DOES appear to have a matching item but trying to remove it via List.Remove just silently fails and doesn't remove the item. I found a workaround by looping through questionList, searching for a matching boardPiece and then removing it via the index (RemoveAt) instead of just using Remove. It doesn't seem to have much of a performance impact since I only have 16 questions at most, but I'd like to know why Remove fails after I deserialize the data so I learn something at least. Mismatching hash or something? I have no idea... :( Here is how I serialize the questionList (it works the same for the boardPieces): ``` XmlSerializer questionListSerializer = new XmlSerializer(typeof(QuestionHelper)); writer.WriteStartElement("QuestionList"); writer.WriteAttributeString("Count", questionList.Count.ToString()); foreach (QuestionHelper question in questionList) questionListSerializer.Serialize(writer, question); writer.WriteEndElement(); ``` and here is how it gets deserialized (same idea for boardPieces again): ``` XmlSerializer questionListSerializer = new XmlSerializer(typeof(QuestionHelper)); int questionListCount = int.Parse(reader.GetAttribute("Count")); reader.Read(); for (int i = 0; i < questionListCount; i++) questionList.Add(questionListSerializer.Deserialize(reader) as QuestionHelper); if (questionListCount > 0) reader.Read(); ```