Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

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

like image 532
Jamie Avatar asked Dec 28 '22 19:12

Jamie


2 Answers

The deserialization process uses FormatterServices.GetUninitializedObject which gets an object without calling any constructor.

like image 144
João Angelo Avatar answered Jan 10 '23 04:01

João Angelo


The serializer doesn't call a constructor when it deserializes an object. The values of the fields are set directly. It doesn't need to create the object (via new) it just creates storage, fills it, and casts it as a Blah type.

like image 23
Chris Eberle Avatar answered Jan 10 '23 05:01

Chris Eberle