1

I have a class implementing ISerializable. Old binary data cannot be deserialized after adding new field to that class due to the following error:

SerializationException: No element named 'x' could be found.

Shouldn't serializer automatically assign null or 0 to that field in this case? I tried using Attribute [OptionalField(VersionAdded = 2)] but with the same result.

I can handle it by checking if field name exists in SerializationEntry array but is this the right way to do it? Is there a better way?

Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
Dave
  • 2,684
  • 2
  • 21
  • 38
  • 1
    Yet another reason against Binary serialization. Do you have a deserialization constructor or are you hoping the framework handles it by itself? – Ron Beyer Apr 30 '18 at 19:14
  • Yes, I do have a deserialization constructor. According to msdn documentation this should be handled by serializer. But I bet it is me doing something wrong... – Dave Apr 30 '18 at 19:17
  • 2
    In that case, you need to show your code. – Ron Beyer Apr 30 '18 at 19:18
  • 1
    If the `SerializationException` is being thrown from a call to `SerializationInfo.GetValue()` from within your own streaming constructor code, then yes, you have to either manually look through the serialization entries, or catch the exception. Once you implement `ISerializable` then you have to do everything manually, attributes like `[OptionalField(VersionAdded = 2)]` no longer matter. – dbc Apr 30 '18 at 19:18
  • Bear in mind `SerializationInfo` was designed as part of .Net 1.0/1.1 (2003-2004) and hasn't really been improved since then. Methods that obviously should be present like `SerializationInfo.TryGetValue()` simply don't exist. – dbc Apr 30 '18 at 19:22
  • Is it better than not to use the ISerializable? – Dave Apr 30 '18 at 19:26
  • 1
    It's better not to use `BinaryFormatter`. See [What are the deficiencies of the built-in BinaryFormatter based .Net serialization?](https://stackoverflow.com/q/703073/3744182). But `ISerializable` itself isn't awful if you need manual control over serialization, it's just that `SerializationInfo` is missing some obviously useful methods. – dbc Apr 30 '18 at 19:29
  • Serializer should include version or other hint data in the serialized data stream so that the deserializer knows what it's looking at. – glenebob Apr 30 '18 at 19:45

0 Answers0