Posts

Showing posts from October, 2012

C# Deserialization and constructor initialization

This is an example how to recreate non serialized member of the class on deserialization.class TestSerialization { [Test] publicvoid Test() { var parent = new Parent(2,3); // serializebyte[] data = SerializationHelper.Serialize(parent); // deserialize var parentCopy = SerializationHelper.Deserialize(data) as Parent; Assert.AreEqual(2, parentCopy.Value1); //confirm that constructor is not called on deserialization Assert.AreEqual(6, parentCopy.Value2); } [Serializable] class Parent { public Parent(intvalue1, intvalue2) { _value1 = value1; _value2 = value2 * 2; //Child object is not serialized, so needs to be recreated on deserialization (see below) _child = new Child() { Value1 = _value1, Value2 = _value2 }; } privateint _value1; privateint _value2; [NonSerialized] private Child _child; publicint Value1 { get { return _child.Value1; } } publicint Value2 { get { return _child.Value2; } } [OnDeserialized] privatevoid Init(Streaming…