What is the difference between [OptionalField] and [NonSerialized]

I came across this question on transcender:

What should be applied to a field if its value is not required during deserialization?

Me = [NonSerialized], ANSWER = [OptionalField]

My gut reaction was NonSerialised, but Transcender says I'm wrong. I have a good idea of ​​what to consider regarding the [Non-Specialized] attribute, but still I really would like this to be clarified.

As far as I can tell, the first one has relationships with version conflicts with older and older versions of the same assembly. The latter is more concerned with not serializing the FULLSTOP field. Is there anything else that could separate the two people? MSDN doesn't really talk about this, since they are both used in BinaryFormatters and SoapFormatter with XMLFormatter using XMLIgnoreAttribute.

My second question is: can you mix and match one of the two attributes? I have not used them yet.

Just tossing it, but my answer has to do with the [OnDeserialized] method and the IdeserilizationCallback interface is implemented?

UPDATE:

I know that the optional field attribute does not serialize the value held by the data member, but NonSerialized will not even serialize the data item or its value.

+6
c #
source share
2 answers

These two attributes are used for the opposite sides of the serialization equation.

When you use [NonSerialized] , you say: β€œThis field should not be serialized at all” - so this is more of a β€œsave time” attribute. Basically, you say that this field does not matter for the serialized state of the object.

When you use [OptionalField] , on the other hand, you are still going to serialize this field. However, if the field is absent during reading (when the stream is deserialized into an object), then the exception will not be raised. This attribute is really designed so that you can add a new field to an existing serializable type without breaking compatibility. Older versions of the object (which are not in this field) will be deserialized as usual.

+6
source share

A simple reproduction of the English language, not required and optional, means the same thing in this case.

For your first question, you pretty much nailed it to your head. [OptionalField] basically allows older serialization to be compatible with newer definitions. [NonSerialized] means you will not find it in serialized data.

Given the differences, I can't imagine why you put both in the same field, but I would suggest that the compiler would complain.

+1
source share

All Articles