ISerializable
is used to provide custom binary serialization, usually for BinaryFormatter
(and perhaps for remoting purposes). Without it, it uses the fields, which can be:
- inefficient; if there are fields that are only used for efficiency at runtime, but can be removed for serialization (for example, a dictionary may look different when serialized)
- inefficient; as even for fields that are needed it needs to include a lot of additional metadata
- invalid; if there are fields that cannot be serialized (such as event delegates, although they can be marked
[NonSerialized]
) - brittle; your serialization is now bound to the field names – but fields are meant to be an implementation detail; see also Obfuscation, serialization and automatically implemented properties
By implementing ISerializable
you can provide your own binary serialization mechanism. Note that the xml equivalent of this is IXmlSerializable
, as used by XmlSerializer
etc.
For DTO purposes, BinaryFormatter
should be avoided – things like xml (via XmlSerializer
or DataContractSerializer
) or json are good, as are cross-platform formats like protocol buffers.
For completeness, protobuf-net does include hooks for ISerializable
(allowing you to use a portable binary format without writing lots of code), but BinaryFormatter
wouldn’t be your first choice here anyway.