CA2239: Provide deserialization methods for optional fields
Visual Studio 2010
TypeName | ProvideDeserializationMethodsForOptionalFields |
CheckId | CA2239 |
Category | Microsoft.Usage |
Breaking Change | Non Breaking |
A type has a field that is marked with the System.Runtime.Serialization.OptionalFieldAttribute attribute and the type does not provide de-serialization event handling methods.
The OptionalFieldAttribute attribute has no effect on serialization; a field marked with the attribute is serialized. However, the field is ignored on de-serialization and retains the default value associated with its type. De-serialization event handlers should be declared to set the field during the de-serialization process.
The following example shows a type with an optional field and de-serialization event handling methods.
using System; using System.Reflection; using System.Runtime.Serialization; [assembly: AssemblyVersionAttribute("2.0.0.0")] namespace UsageLibrary { [SerializableAttribute] public class SerializationEventHandlers { [OptionalFieldAttribute(VersionAdded = 2)] int optionalField = 5; [OnDeserializingAttribute] void OnDeserializing(StreamingContext context) { optionalField = 5; } [OnDeserializedAttribute] void OnDeserialized(StreamingContext context) { // Set optionalField if dependent on other deserialized values. } } }