Search code examples
c#streamdatacontractserializer

C#: DataContractSerializer and different streams


I'd like to use DataContractSerializer and I'm confused about the Stream parameter in its WriteObject method - I see that I can use either MemoryStream or XmlWriter. I'd like to know:

  • How is the serialization affected by the stream selection? Does it affect the size of the object?
  • When using MemoryStream, do I always get a binary object?

Those questions might be basic, but I've been googling and can't find clear answers. Thanks.


Solution

  • DataContractSerializer is inherently an xml-based serializer. If you pass a Stream, it will construct an XmlWriter (specifically, an XmlDictionaryWriter) that wraps the stream, and then the core serialization code writes to the XmlWriter.

    How is the serialization affected by the stream selection? Does it affect the size of the object?

    Using different Stream instances doesn't affect what happens internally, but there can be slight differences here compared to passing in an XmlWriter, depending on what the encoding is. If you pass a Stream, then DataContractSerializer uses UTF-8; but if you pass it an XmlWriter you can specify different encodings.

    When using MemoryStream, do I always get a binary object?

    MemoryStream is a wrapper over a byte[], and yes: once you've called .ToArray() afterwards you have just binary. However, it is binary that also happens to be xml. It can be both.

    If you want serialization that is actually binary (meaning: fundamentally a binary serialization format, rather than xml / json / csv / etc), then maybe consider something like protobuf-net.