1

Apparently XmlSerializer works smoothly for objects if the instances are not derived, otherwise I'd have to explicitly apply an attribute to include specific derived classes onto the base class. I have around 50+ derived classes and possibly more in the future, is there a way to tell XmlSerializer to just automatically serialize the derived parts of an object and not hassle me to be more explicit with what I want? I just want to type less.

chaz
  • 568
  • 1
  • 8
  • 22

1 Answers1

0

The need to specify them stems primariliy due to complexities of having to deserialize them. At the point of serialization it could, after all, walk the inheritance tree to find information. But consider being asked to deserialize a Foo, but getting a <bar> it is not immediately obvious how to resolve the type.

XmlSerializer, sensibly, wants to be sure it can perform both actions - in the same way that it wants a public parameterless constructor before it will serialize, when clearly serialization doesn't call a constructor. So ultimately: no - you are going to have to tell it the types.

Note that this doesn't mean you red to use XmlIncludeAttribute - you can also supply this info the the XmlSerializer constructor (extra types). However, it is IMO more convenient to use the attribute approach, and "typing less" certainly isn't a good reason not to do it that way. Additionally, if using anything other than the XmlSerializer(Type) constructor you need to cache the serializer to prevent leaking assemblies.

I'd just add the attributes...

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Well imply that "typing less" == "conventional", and that's a good thing. Actually I just want to visualize the information, I don't plan on deserializing. Maybe that extra detail will unravel more options? – chaz Jan 21 '12 at 13:07
  • 1
    @chaz if you just want to visualise, then note that most Jason serializers are more forgiving here – Marc Gravell Jan 21 '12 at 13:09
  • Interesting, but it's representation would seem awkward. What I'm trying to convert into a serialized form is a Code DOM for a compiler so I can better visualize recursive procedures I'm writing. But it's going well without it, thanks for your insight anyways. – chaz Jan 21 '12 at 14:14