Serialization
//data must be [Serializable]
MyObjectType data = new MyObjectType();
MemoryStream stm = new MemoryStream();
// Serialize
IFormatter f = new BinaryFormatter(); //XmlSerializer, SoapFormatter
f.Serialize(stm, data);
// DeSerialize
stm.Seek(0, SeekOrigin.Begin);
IFormatter ds = new BinaryFormatter();
data = (MyObjectType)ds.Deserialize(stm);
- See msdn
- You must use [Serializable] on the class. It is NOT inherited.
- [DataContract]/[DataMember] is more flexible. Use [DataMember] to get rid of ugly k__BackingField serialization.
- XmlSerializer does not serialize private fields, but BinarySerializer does.
- Non-serializable event subscribers can be grabbed as well so decorate events with [field: NonSerialized]
- Generic collections are serializable but not generic Dictionary.
- To reinitialize [NonSerializable] members, implement IDeserializationCallback (void IDeserialization.OnDeserialization()).
- 2.0- For BinaryFormatter- you can create 4 events with attributes [OnDeserializing / OnDeserialization] (methods must take a StreamingContext).
[OnDeserialization] is much the same as IDeserializationCallback. - [OptionalField] - when deserialized, no error if not there (versioning) 2.0
- SoapFormatter- unlike BinaryFormatter, you must reference the *.soap.dll
- xmlSerializer- only public members and parameterless ctor. [XmlIgnore]=[NonSerialized]. Ctor takes the typeof(obj) NB if you use other overloaded ctors, dynamically generated assemblies are never unloaded... (you can use SGEN.exe to initialize them in 2.0)
- Custom serialization by implementing ISerializable.
- GetObjectData(SerializationInfo info, StreamingContext sc) serializes manually: info.AddValue("my name2", _var)
- #ctor(SerializationInfo info, StreamingContext sc) : _var= info.GetDecimal("my name");
- In both StreamContext.State is a enum of whether to file/db (Presistence) or cross machine etc
//xmlserializer
var serializer = new XmlSerializer(typeof(Product));
using (var sw = new StringWriter())
{
serializer.Serialize(sw, product);
var xml = sw.ToString();
}
//datacontract serializer
var dcs = new DataContractSerializer(typeof(Product));
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw))
{
dcs.WriteObject(xw, product);
}
var xml = sw.ToString();
}