Serializing Types with Subclasses: A Robust Solution

  • Thread starter Thread starter twoski
  • Start date Start date
  • Tags Tags
    Type
Click For Summary
The discussion centers on the challenge of serializing a base class and its subclasses in .NET when the original class is not serializable. A solution involves creating a serializable version of the class with conversion methods, but issues arise when handling multiple subclasses that share similar data structures. The need for a generic method to save and instantiate the specific subclass during deserialization is highlighted. One proposed approach is to use a string or enum to identify the class type, though this is considered a hacky solution. The use of reflection is suggested as a more robust method to dynamically instantiate the correct subclass based on its name during deserialization.
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
I'm sorry you are not finding help at the moment. Is there any additional information you can share with us?
 
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.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 8 ·
Replies
8
Views
1K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 43 ·
2
Replies
43
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K