CA2239: Provide deserialization methods for optional fields

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA2239
Category Microsoft.Usage
Breaking change Non-breaking

Cause

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.

Rule description

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.

How to fix violations

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

When to suppress warnings

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

Example

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.
      }
   }
}
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

CA2236: Call base class methods on ISerializable types

CA2240: Implement ISerializable correctly

CA2229: Implement serialization constructors

CA2238: Implement serialization methods correctly

CA2235: Mark all non-serializable fields

CA2237: Mark ISerializable types with SerializableAttribute

CA2120: Secure serialization constructors