whenever I try to serialize an object that has an IEnumerable collection I get a big dirty error telling me it can’t serialize it because it’s an interface. Now I get why it’s happening but it raises some other questions for me. Like if I intend on having collections within my objects AND I want to serialize them do I need to resort to
- Using List<>, CollectionBase, ReadOnlyCollectionBase in my objects.
- Making my objects implement the IXmlSerializable interface.
- Decorating my classes with horrible attributes.
- Writing my own serializer.
What is the best practice way to go?
Speaking as a serializer author, I know exactly why it gets very hard to robustly work just from
IEnumerable<T>, especially for “get-only” properties. You might tryIList<T>(although it wouldn’t amaze me if it wants a concrete type such asList<T>/T[]), but I suspect the real problem here is that you trying to use one model to do two things, and are unhappy at having to compromise to do it.Fine: if you don’t want to compromise your domain model, write a separate DTO model that is used for serialization, and just map between them. This is usually trivial, and will allow the serializer and the domain model to each excel at their one job. It will also help immensely when you need to “version” the system or introduce a different serializer (JSON, protobuf, etc).
Re your bullets:
Addetc will workXmlAttributeOverrides, but watch out for leaking assemblies if you do this)