Share via


CA2238: Implement serialization methods correctly

Note

This article applies to Visual Studio 2015. 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

For the latest documentation on Visual Studio, see CA2238: Implement serialization methods correctly.

Item Value
TypeName ImplementSerializationMethodsCorrectly
CheckId CA2238
Category Microsoft.Usage
Breaking Change Breaking - If the method is visible outside the assembly.

Non-breaking - If the method is not visible outside the assembly.

Cause

A method that handles a serialization event does not have the correct signature, return type, or visibility.

Rule Description

A method is designated a serialization event handler by applying one of the following serialization event attributes:

How to Fix Violations

To fix a violation of this rule, correct the signature, return type, or visibility of the serialization event handler.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

The following example shows correctly declared serialization event handlers.

using System;
using System.Runtime.Serialization;

namespace UsageLibrary
{
   [SerializableAttribute]
   public class SerializationEventHandlers
   {
      [OnSerializingAttribute]
      void OnSerializing(StreamingContext context) {}

      [OnSerializedAttribute]
      void OnSerialized(StreamingContext context) {}

      [OnDeserializingAttribute]
      void OnDeserializing(StreamingContext context) {}

      [OnDeserializedAttribute]
      void OnDeserialized(StreamingContext context) {}
   }
}
Imports System
Imports System.Runtime.Serialization

Namespace UsageLibrary

   <SerializableAttribute> _ 
   Public Class SerializationEventHandlers

      <OnSerializingAttribute> _ 
      Private Sub OnSerializing(context As StreamingContext) 
      End Sub

      <OnSerializedAttribute> _ 
      Private Sub OnSerialized(context As StreamingContext) 
      End Sub

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

      <OnDeserializedAttribute> _ 
      Private Sub OnDeserialized(context As StreamingContext)
      End Sub

   End Class

End Namespace

CA2236: Call base class methods on ISerializable types

CA2240: Implement ISerializable correctly

CA2229: Implement serialization constructors

CA2235: Mark all non-serializable fields

CA2237: Mark ISerializable types with SerializableAttribute

CA2239: Provide deserialization methods for optional fields

CA2120: Secure serialization constructors