Provide deserialization methods for optional fields
TOC
Collapse the table of content
Expand the table of content

Provide deserialization methods for optional fields

TypeName

ProvideDeserializationMethodsForOptionalFields

CheckId

CA2239

Category

Microsoft.Usage

Breaking Change

NonBreaking

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.

To fix a violation of this rule, add de-serialization event handling methods to the type.

It is safe to exclude a warning from this rule if the field should be ignored during the de-serialization process.

The following example shows a type with an optional field and de-serialization event handling methods.

Imports System
Imports System.Reflection
Imports System.Runtime.Serialization

<Assembly: AssemblyVersionAttribute("2.0.0.0")>
Namespace UsageLibrary

   <SerializableAttribute> _ 
   Public Class SerializationEventHandlers

      <OptionalFieldAttribute(VersionAdded := 2)> _ 
      Dim optionalField As Integer = 5

      <OnDeserializingAttribute> _ 
      Private Sub OnDeserializing(context As StreamingContext)
         optionalField = 5
      End Sub

      <OnDeserializedAttribute> _ 
      Private Sub OnDeserialized(context As StreamingContext)
         ' Set optionalField if dependent on other deserialized values.
      End Sub

   End Class

End Namespace

Community Additions

ADD
Show:
© 2016 Microsoft