Serializing Types with Subclasses: A Robust Solution

  • Thread starter Thread starter twoski
  • Start date Start date
  • Tags Tags
    Type
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 1K views
twoski
Messages
177
Reaction score
2
Let's say i have a class which is not my own code. It is not serializable using the .NET serialization utilities.

In order to save the pertinent data for this class i have created a serializable version of the class and have conversion methods which allow me to essentially convert the class to a serailization friendly class.

This works fine if there is only one class, but what if i have several subclasses deriving from this class?

From the serialization perspective, it would be impossible to distinguish one from another. All of them have more or less the same data. Their type is the only thing that differs.

How can i make a generic method for saving the class type, and then instantiating that specific type when i deserialize?

One way i could do it is save a string/enum that tells me what class to instantiate when i deserialize. This sounds hacky to me though. There must be a better, more robust solution.
 
Physics news on Phys.org
Someone on another forum told me that the solution to this would be using reflection, not sure exactly how it would work though.

I would get the string name of a class (there is some method of doing this, not sure what it is though) and use reflection to instantiate that class using the string name when i deserialize.