I have a singleton class called Manager that holds a list of object instances:
static class Manager
{
static List<Foo> Foos = new List<Foo>();
}
I then have a collection of object instances using a class called Meter that uses references to items in the list Foos:
class Meter
{
public Foo MyFoo = null;
}
...
public void CreateMeter(int UserChoice)
{
Meter MyMeter = new Meter();
MyMeter.MyFoo = Manager.Foos[UserChoice];
}
When the application saves a project file it serializes the instances of Foo in Foos along with all the instances of Meter.
My problem is how to deserialize this arrangement. Currently I do the following:
- Deserialize the project-wide instances of Foo to reconstruct Manager.Foos
- Deserialize a meter instance which includes an instance of Foo for the MyFoo property
- Search Manager.Foos and find the matching reference for MyMeter.MyFoo and then assign the reference from Manager.Foos.
This seems to me clunky and not too easy to extend. I would rather that the Meter factory doesn’t need to search Manager.Foos during deserialization because in future Meter might take it’s refence to a Foo instance from other places, not just Manager.
Is there a simple but flexible alternative solution to this deserialization problem where references to objects can be easily reconstructed?
Thanks Marc and everyone else for the suggestions. Based on Marc’s key idea and Henk’s object id generator here is what I have so far.
Foo defines a Guid property which contains a unique Guid. This is generated in the constructor but can also be saved/restored with serialization/deserialization.
Meter no longer uses a reference, instead it uses a Guid:
When a meter is created the Guid establishes the connection:
When Meter is serialized/deserialized the Guid is stored/loaded.
One downside is when the Foo instance associated with a meter needs to be accessed. Instead of directly using the reference a lookup has to be performed which will incur a performance hit:
A benefit of this approach is that now I can create a delegate and have multiple sources of Foo to associate with meters: