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.
DataContractSerializeris inherently an xml-based serializer. If you pass aStream, it will construct anXmlWriter(specifically, anXmlDictionaryWriter) that wraps the stream, and then the core serialization code writes to theXmlWriter.Using different
Streaminstances doesn’t affect what happens internally, butthere can be slight differences here compared to passing in an
XmlWriter, depending on what the encoding is. If you pass aStream, thenDataContractSerializeruses UTF-8; but if you pass it anXmlWriteryou can specify different encodings.MemoryStreamis a wrapper over abyte[], 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.