CA2237: Mark ISerializable types with SerializableAttribute

 

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

For the latest documentation on Visual Studio 2017, see CA2237: Mark ISerializable types with SerializableAttribute on docs.microsoft.com.

TypeNameMarkISerializableTypesWithSerializable
CheckIdCA2237
CategoryMicrosoft.Usage
Breaking ChangeNon Breaking

An externally visible type implements the System.Runtime.Serialization.ISerializable interface and the type is not marked with the System.SerializableAttribute attribute. The rule ignores derived types whose base type is not serializable.

To be recognized by the common language runtime as serializable, types must be marked with the SerializableAttribute attribute even if the type uses a custom serialization routine through implementation of the ISerializable interface.

To fix a violation of this rule, apply the SerializableAttribute attribute to the type.

Do not suppress a warning from this rule for exception classes because they must be serializable to work correctly across application domains.

The following example shows a type that violates the rule. Uncomment the SerializableAttribute attribute line to satisfy the rule.

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);
      }
   }
}

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

CA2239: Provide deserialization methods for optional fields

CA2120: Secure serialization constructors

Show: