Thursday, October 27, 2011

Serialization lost

Just a side note.

When an object is been deserialized by IFormatter, no constructors are called*! So if you have any fields marked as [NonSerialized] that are initilized in constructors or inline, they would not be initialized at all!

Consider the following example:

[Serializable]
public class Test
{
 public Test()
 {
  Console.WriteLine("Inside ctor");
 }

 [NonSerialized]
 private readonly string _nonSerizlied = "Non serialized";

 private readonly string _serizlied = "Serialized";

 public override string ToString()
 {
  return string.Format("NonSerizlied: {0}, Serizlied: {1}"_nonSerizlied_serizlied);
 }
}
 
 
static void Main(string[] args)
{
 Test test = new Test();

 Console.WriteLine(test);

 IFormatter formatter = new BinaryFormatter();
 using (var stream = new MemoryStream())
 {

  formatter.Serialize(stream, test);

  stream.Position = 0;

  test = (Test) formatter.Deserialize(stream);

  Console.WriteLine(test);
 }
} 
 
The output will be:

Inside ctor
NonSerizlied: Non serialized, Serizlied: Serialized
NonSerizlied: , Serizlied: Serialized

So _nonSerizlied  field is not initialized at all and constructor is not called.

* If a type realized ISerializable, the serialization constructor will be called, but the default one will be not as well.


 

No comments:

Post a Comment