In. Net you can mark a field as non serializable, and it will be skipped during serialization.
I’m looking for a simple method that will allow me to control in runtime whether a specific field should be serialized.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are referring to “mark a field as non serializable”, so I assume you are using
BinaryFormatterand[NonSerialized]. If so, the only way to do conditional serialization is by implementingISerializableand adding a similar constructor, and putting the logic in theGetObjectDataimplementation. This is tedious and error prone, though. I would suggest looking at protobuf-net, which has simpler conditional serialization, using the standard patterns used byTypeDescriptorandXmlSerializer, but is still binary output (more efficient thanBinaryFormatter, actually). Specifically:This
ShouldSerialize*is a standard name-based convention – nothing specific to this serializer.Here’s the same via
ISerializable:Lots more to maintain; in particular, you have to take responsibility for all members when using
ISerializable– however, if you just use protobuf-net you can handle each on a case-by-case basis.Actually, you can mix-and-match too, i.e. if you are stuck with using
BinaryFormatter, you can still offload the work to protobuf-net, but it will change the format (so won’t be compatible with old data). For example: