.NET BinaryFormatter - Shallow copy instead of deep copy?

Vai

Vai

Soldato
Joined
18 Oct 2002
Posts
3,347
Hi,

I am storing the data in my application in a file so I can save/load between sessions.

I have class X, which contains a List that stores other objects of class X, to create a tree structure.
In my application I have a field which is a reference to the current object X that the user is looking at.
The problem I am having is that BinaryFormatter is doing a deep copy of the objects, rather than a shallow copy, so when I load the file the reference field is no longer pointing to an object within the tree, but to a copy.

I could add an ID int to the class and then search through the tree after it has been loaded to get a new reference, but it feels like a poor workaround to me.

Is there a solution to this without resorting to ditching BinaryFormatter and manually writing a way to store the objects in the file?

[edit]

Never mind, it appears it does work if you combine the two into an array and serialize/deserialize at the same time.
 
Last edited:
BinaryFormatter does retain referencing but, yes, as you figured out, you have to serialize all objects in the tree as a single go. You can't split the serialization up into many sub-trees because then you will start losing the referencing that you expected to retain.

Serialization is neat isn't it?
 
Back
Top Bottom