Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much does a class/object have to change in order for binary-deserialization to fail

We have a solution where we are storing a fairly large/complex C# object in our database as binary data. My concern is that when changes are made to this class, we run the risk that data saved to the database will fail on deserialization after the code change.

Here are is the code we're using to serialize objects:

    public static byte[] SerializeObject(object toBeSerialized)
    {
        var stream = new MemoryStream();
        var serializer = new BinaryFormatter();
        serializer.Serialize(stream, toBeSerialized);
        stream.Position = 0;
        return stream.ToArray();
    }

Here is our Deserialize method:

    public static T DeserializeObject<T>(byte[] toBeDeserialized)
    {
        using (var input = new MemoryStream(toBeDeserialized))
        {
            var formatter = new BinaryFormatter();
            input.Seek(0, SeekOrigin.Begin);
            return (T) formatter.Deserialize(input);
        }
    }

My question is, what has to change/how much has to change in order for deserialization of an older object to fail?

like image 230
Ben Avatar asked May 14 '15 14:05

Ben


2 Answers

Always make serialization version tolerance, in this article you can find some advice how to do it

Also you can find some cases, that break serialization/deserialization below

  • When you remove a serialized field

  • When you apply the NonSerializedAttribute attribute to a field if the attribute was not applied to the field in the previous version.

  • When you change the name or the type of a serialized field.

  • When adding a new serialized field, without OptionalFieldAttribute attribute.

  • When removing a NonSerializedAttribute attribute from a field (that was not serializable in a previous version), without the OptionalFieldAttribute attribute.

like image 179
Arsen Mkrtchyan Avatar answered Sep 23 '22 05:09

Arsen Mkrtchyan


Any changes to the data structures (properties and fields) of the class will cause you problems when trying to deserialize the data.

I know for sure that changing the definition of a method will cause you no problems, and adding or removing methods is similarly fine.

EDIT: I've done a little test on a similar system I've developed and I've found you can add new properties and fields and still deserialize the old object. It seems to me the only problem you'll have is if you delete, rename, or change the type of existing fields and properties.

Related Question

like image 26
Slappywag Avatar answered Sep 25 '22 05:09

Slappywag