When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output ‘After Serialization: true’.
class Program { static void Main(string[] args) { MyObject obj = new MyObject() { Name = 'obj' }; MyObject[] myObjs = new MyObject[] { obj, obj }; Console.WriteLine('Object Refs Equal?'); Console.WriteLine(string.Format('Before Serialization: {0}', object.ReferenceEquals(myObjs[0], myObjs[1]))); XmlSerializer toXml = new XmlSerializer(typeof(MyObject[])); using (FileStream toFile = File.Create(@'C:\foo.xml')) { toXml.Serialize(toFile, myObjs); } XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[])); using (FileStream fromFile = File.OpenRead(@'C:\foo.xml')) { MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile); Console.WriteLine(string.Format('After Serialization: {0}', object.ReferenceEquals(deserialized[0], deserialized[1]))); } Console.ReadLine(); } } [Serializable] public class MyObject { public string Name { get; set; } }
If you’re using .NET 3 or later, you should use the
DataContractSerializerand setPreserveObjectReferencestotrue.