1

I am using binary serialization (with BinaryFormatter, etc) to serialize a graph of objects. Of those objects, some have fields of a certain type that is similar to an enumeration, except with additional properties and methods.

The problem that every time this enum-like object gets deserialized, a new instance of the type is created. Is there some sort of special deserialization method that allows you to return one of a set of existing objects, instead of creating a completely new one?

I've heard of ways to do this per type containing the enum-like object, but I would rather make it so that any class containing the enum-like object will automatically deserialize it by looking in the existing objects of the enum-like type.

(Why I want this, in case it matters

  1. Equality becomes easier, I can just use the default reference-comparing operators instead of having to override Equals, GetHashCode, ==, and != and implement IEquatable.

  2. Some of the data in the enum-like object may change, and I want the serialized data to update to the new data without lots of code. (Note that there is a field in the enum-like object that will never change.))

Jamie
  • 3,901
  • 3
  • 23
  • 27

1 Answers1

1

You would do this with ISerializationSurrogate.

See here for some example code.

Update

In my case, I need to re-use existing (boxed) instances for the SymbolId and bool value types.

leppie
  • 115,091
  • 17
  • 196
  • 297