Having issues with serialization and upward compatibility

Hey,
for my savegame serialization i’m using the BinaryFormatter.
In one of the serialized classes i had a property

public Vector2 Position { get; set; }

I serialized some data, then i changed this property to have a proper get { … } implementation that does a little bit more logic. Now, if i try to load the data that i serialized before, i get the following serialization exception:

“k__BackingField” not found"

this would mean, my game would not be able to load savegames that where made before that change - so no chance for any upward compatibility. How do i resolve or avoid this issue?

Declare your backing fields explicitly:

[Serializable]
private Vector2 _position;

public Vector2 Position
{
    get { return _position; }
    set { _position = value; }
}

(BinaryFormatter wasn’t serializing your property directly; it was serializing the auto-generated backing field. If you provide your own logic, you need to mark the backing field serializable using the [Serializable] attribute.)

Alternatively, you could implement ISerializable, but that would just be hacking around the issue.

2 Likes