Are these fields set to default values like when a new instance is created? Can I create custom code to set these fields to new values upon deserialization?
Share
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.
Note: all of this is specific to
BinaryFormatter:By default, they are ignored completely; they will have their type-default values, i.e. a zero-value / null-value.
If you implement custom serialization (
ISerializable), then[NonSerializable]doesn’t apply, and you can do what you want, but most people don’t want to have to do this. However, you can also implementIDeserializationCallback, which provides an ideal opportunity to initialize such fields:Note that other serializers have different implementations for serialization callbacks, some of which are also supported by
BinaryFormatter, for example:The attribute-based callbacks provide more opportunities to inject code at specific points, and are usually preferred. There are 4:
[OnDeserializing],[OnDeserialized],[OnSerializing]and[OnSerialized].