Renaming fields, then deserialization in C #

I have data stored in an instance of a class that has been serialized with .net BinaryFormatter. Now I want to rename one of the fields in the class, but still be able to deserialize the old data.

One option is to implement ISerializable and deserialize all the fields of the class manually. But this seems like a lot of work, especially if my class has many fields, and I just renamed one field.

Is there a better way?


Craig suggests saving a copy of the old class for deserialization and copying the values ​​into the new class. I also saw this elsewhere - what advantage does this have for implementing ISerializable? As far as I see, copying the class leaves me with 2 almost identical copies of the class, plus I still have to copy all the values ​​from the old class to the new class, which seems to be the same amount of work as implementing ISerializable using an almost duplicated class thrown into mix


Two answers mention Binders. I successfully used the SerializationBinder to deserialize the Bar class, which was serialized as the Foo class, but this is because the class name has changed. Does SerializationBinder help when you rename a field - say, when int m_Left was renamed to int m_Right?

+6
c # serialization
source share
4 answers

You can try to let the old calss hang for the sole purpose of rehydration, and then just copy the fields you need for the new class. It still hurts, but it should work.

+2
source share

Yes, this is a problem with field serializers. You can use either a custom Binder or a “serialization surrogate” to avoid implementing ISerializable , but this is only a random solution.

I discussed this topic (in the context of obfuscators and auto details) here . My advice: do not use BinaryFormatter to save data between versions ... for this, look at contract based serializers:

  • XmlSerializer
  • DataContractSerializer
  • or for binary code like protobuf-net

None of this will help you today, but it can help you create designs around it in the future.

+2
source share

I used the SerializationBinder class for this before

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationbinder.aspx

it can be used for deserialization, so you can reassign the old type to the new one.

0
source share

What to do if you just change the access modifier to this property to private, and then get a public property with a new name that just basically wraps the old one. That way you can still deserialize (I THINK), but anyone using this class will not know about the old name. Just a thought ...

0
source share

All Articles