Export (0) Print
Expand All
Expand Minimize

CA2236: Call base class methods on ISerializable types

TypeName

CallBaseClassMethodsOnISerializableTypes

CheckId

CA2236

Category

Microsoft.Usage

Breaking Change

Non Breaking

A type derives from a type that implements the System.Runtime.Serialization.ISerializable interface, and one of the following conditions is true:

In a custom serialization process, a type implements the GetObjectData method to serialize its fields and the serialization constructor to de-serialize the fields. If the type derives from a type that implements the ISerializable interface, the base type GetObjectData method and serialization constructor should be called to serialize/de-serialize the fields of the base type. Otherwise, the type will not be serialized and de-serialized correctly. Note that if the derived type does not add any new fields, the type does not need to implement the GetObjectData method nor the serialization constructor or call the base type equivalents.

To fix a violation of this rule, call the base type GetObjectData method or serialization constructor from the corresponding derived type method or constructor.

Do not suppress a warning from this rule.

The following example shows a derived type that satisfies the rule by calling the serialization constructor and GetObjectData method of the base class.

using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace UsageLibrary
{
   [SerializableAttribute]
   public class BaseType : ISerializable
   {
      int baseValue;

      public BaseType()
      {
         baseValue = 3;
      }

      protected BaseType(
         SerializationInfo info, StreamingContext context)
      {
         baseValue = info.GetInt32("baseValue");
      }

      [SecurityPermissionAttribute(SecurityAction.Demand, 
          SerializationFormatter = true)]
      public virtual void GetObjectData(
         SerializationInfo info, StreamingContext context)
      {
         info.AddValue("baseValue", baseValue);
      }
   }

   [SerializableAttribute]
   public class DerivedType : BaseType
   {
      int derivedValue;

      public DerivedType()
      {
         derivedValue = 4;
      }

      protected DerivedType(
         SerializationInfo info, StreamingContext context) : 
         base(info, context)
      {
         derivedValue = info.GetInt32("derivedValue");
      }

      [SecurityPermissionAttribute(SecurityAction.Demand, 
          SerializationFormatter = true)]
      public override void GetObjectData(
         SerializationInfo info, StreamingContext context)
      {
         info.AddValue("derivedValue", derivedValue);
         base.GetObjectData(info, context);
      }
   }
}
Show:
© 2014 Microsoft