0

I am trying to use Polymorphism with data that is to be serialized and deserialized. However, it seems that the polymorphic properties are being lost on serialization:

// Serialize
[System.Serializable]
public ParentClass()
{
  public string someString = "a string";
}
[System.Serializable]
public ChildClass() : ParentClass
{
  public int someInt;
  public ChildClass(int _someInt)
  {
    someInt = _someInt;
  }
}

List<ParentClass> list = new List<ParentClass>();
list.Add(new ChildClass(5));

// Data is serialized

// Data is deserialized

Debug.Log(list[0].someString);
// Output: a string; Works as intended

Debug.Log((list[0] as ChildClass).someInt));
// Null Reference Exception

How can you properly serialize these classes in this case?

LostPhysx
  • 3,573
  • 8
  • 43
  • 73
Abdulla
  • 1,117
  • 4
  • 21
  • 44
  • How do you serialize and deserialize the types? Using `BinaryFormatter`? XML serialization? Something else? Could you include your (de-)serialization code? – svick Apr 28 '12 at 10:10
  • 1
    You don't serialize "classes" - you serialize *objects*. Please explain exactly what you are doing... For example, are you talking about a WSDL/MEX-generated client proxy type? (i.e. a WCF or SOAP service)? Or: what serializer are you using? Please show the "data is saved" / "data is loaded" code. – Marc Gravell Apr 28 '12 at 10:12
  • 2
    Also: nothing in that is polymorphic! Polymorphism in c# is based on the `override`, `virtual`, `abstract` and `sealed` keywords - which you don't use. – Marc Gravell Apr 28 '12 at 10:14
  • Actually, I am writing editor scripts for the Unity game engine. The Unity editor handles serializing and de-serializing code automatically. I'll do some digging to find out how this is done. @Marc Looks like I gotta brush up on my C# – Abdulla Apr 28 '12 at 10:15
  • 2
    @Abdulla then the real question is: "does the Unity serialization support *inheritance*?" (inheritance!=polymorphism). You can always handle the serialization yourself, of course, using your choice of serializer - and just give unity the blob/clob. – Marc Gravell Apr 28 '12 at 10:17
  • Thanks a lot for the insight, needed a nudge in the right direction. – Abdulla Apr 28 '12 at 10:20
  • Could be helpful to look at http://stackoverflow.com/questions/1619997/xml-deserialization-of-inherited-objects and it might be a problem if you have no parameterless constructor. – erikH Apr 28 '12 at 11:31
  • If you provide the code you are using for // Data is saved and // Data is loaded...it would be easier to point you in the right direction. – Eric Dahlvang Apr 28 '12 at 13:53

0 Answers0