views:

27

answers:

1

I'm implementing some custom serialization (to byte array), and have run into a problem handling circular references.

Example:

Class A
  public MyBs as new List(of B)

end class

class B
  public MyParent as A
  public MiscInt1 as integer
  public MiscInt2 as integer

end class

When serializing A, I must serialize each instance of B.

However, I have a problem when serializing B.

How do I record the parent of B without causing an infinite loop?

An idea:

If I know that an instance of B will only ever be serialized through the serialization of an instance of A, then I can handle the setup of the MyParent reference from the instance of A and not even record that information inside the byte buffer for the instance of B

This doesn't feel quite right, but it might be the best solution.

Is there a cleaner way of handling this situation?

+1  A: 

You can use approach similar to standard BinaryFormatter from BCL: utilize ObjectIDGenerator and store reference id instead of object in case of circular references

desco
How do you know the type of the reference that you're restoring during deserialization? Are you just inferring it based upon context?
hamlin11
Builtin implemetation stores object identifier (plus type related information at first occurance of object instance): (A-1)(ListB-2)(B-3)(ref-1)(10)(20)(B-4)(ref-1)(100)(200). When identifier is met for the first time you store id and deserialized object. On latter appearances of this identifier you will take existing object.
desco