Chapter 5. Serialization.
1. How to serialize an object.
In order to be able to serialize type it needs to be marked with [Serialized] attribute.
[Serializable]
class ObjectToBeSerialized
{
}
We can serialize such object like this:
1: using System;2: using System.IO;3: using System.Runtime.Serialization.Formatters.Binary;4:5: [Serializable]6: class ObjectToBeSerialized7: {8: }9:10: class Program11: {12: void Serialize()13: {14: ObjectToBeSerialized instance = new ObjectToBeSerialized();15:16: using (FileStream stream = File.Create( @"c:/output.bin"))17: {18: BinaryFormatter formatter = new BinaryFormatter();19: formatter.Serialize(stream, instance);20: }21: }22: }
2. How to deserialize object.
1:2: using (FileStream stream = File.Open(@"c:/output.bin", FileMode.Open))3: {4: BinaryFormatter formatter = new BinaryFormatter();5: ObjectToBeSerialized instance = (ObjectToBeSerialized )formatter.Deserialize(stream);6: }7:
3. How to handle values that are calculated / do not have to be serialized.
1: using System.Runtime.Serialization;2: using System;3:4: [Serializable]5: class ObjectToBeSerialized : IDeserializationCallback6: {7: private int m_value1;8:9: [NonSerialized]10: private int m_value2;11:12: public ObjectToBeSerialized( int _value1)13: {14: m_value1 = _value1;15: m_value2 = 10; // calculated value16: }17:18: public void OnDeserialization(object sender)19: {20: m_value2 = 10;21: }22: }23:
If we don’t want some fields to be serialized we mark them with [NonSerialized].
If we have some values that are not serialized but have to be initialized we can use IDeserializationCallback interface to handle that.
4. Serialization and version compatibility.
Advertisement
Leave a Comment