How does serialization work without constructors?

I'm not sure how this piece of code works.

[Serializable] class Blah { public Blah(int value) { this.value = value; } public int value; } BinaryFormatter b = new BinaryFormatter(); Blah blah = new Blah(4); MemoryStream s = new MemoryStream(); b.Serialize(s, blah); s.Seek(0, SeekOrigin.Begin); blah = null; blah = (Blah)b.Deserialize(s); 

Since I don't have a constructor without parameters, it seems strange that the deserializer can create a new instance of Blah.

+4
source share
3 answers

The deserialization process uses FormatterServices.GetUninitializedObject , which receives the object without calling any constructor.

+5
source

The serializer does not call the constructor when the object is deserialized. Field values ​​are set directly. He does not need to create an object (via new ), he just creates a repository, fills it and distinguishes it as a Blah type.

+4
source

BinaryFormatter uses the voodoo method called FormatterServices.GetUninitializedObject :

... the object is initialized to zero and no constructors are started

+1
source

All Articles