Question

I came across this question on transcender:

What should you apply to a field if its value is not required during deserialization?

Me = [NonSerialized], ANSWER = [OptionalField]

My gut reaction was NonSerialised but Transcender says I am wrong. I have a good idea what to look out for as far as the [Nonseralized] attribute is concerned but still I would really like this cleared up.

As far as I can tell the former has a relationship with versioning conflicts between newer and older versions of the same assembly. The latter is more concerned with not serializing a field FULLSTOP. Is there anything else that might set these two apart? MSDN does not really say much about this as they both are used on the BinaryFormatters and SoapFormatter with the XMLFormatter using the XMLIgnoreAttribute.

My second question is can you mix and match either one of the two attributes? I have yet to use them.

Just throwing this one out there, but does my answer have something to do with the way [OnDeserialized] and the IdeserilizationCallback interface is implemented?

UPDATE:

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

Was it helpful?

Solution

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

When you use [NonSerialized], you're saying "this field should not be serialized at all" - so it's more of a "save time" attribute. Basically, you're saying that field does not matter for the serialized state of the object.

When you use [OptionalField], on the other hand, you're still going to serialize the field. However, if the field is missing at read time (when the stream is deserialized into an object), then no exception will be raised. This attribute is really intended to allow you to add a new field to an existing serializable type, without breaking compatibility. Older versions of the object (which are missing that field) will be deserialized normally.

OTHER TIPS

Just playing off the English language, not required and optional mean the same thing in this case.

For your first question, you pretty much nailed it on the head. [OptionalField] basically allows older serializations to be compatible with newer definitions. [NonSerialized] means that you won't find it in the serialized data.

Given the differences, I can't imagine why you'd put both on a single field but I would guess the compiler would complain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top