Edit

Share via


CA2237: Mark ISerializable types with SerializableAttribute

Property Value
Rule ID CA2237
Title Mark ISerializable types with SerializableAttribute
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

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.

Rule description

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.

How to fix violations

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

When to suppress warnings

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

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2237
// The code that's violating the rule is on this line.
#pragma warning restore CA2237

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2237.severity = none

For more information, see How to suppress code analysis warnings.

Example

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

Imports System.Runtime.Serialization

Namespace ca2237

    ' <SerializableAttribute> _ 
    Public Class BaseType
        Implements ISerializable

        Dim baseValue As Integer

        Sub New()
            baseValue = 3
        End Sub

        Protected Sub New(
         info As SerializationInfo, context As StreamingContext)

            baseValue = info.GetInt32("baseValue")

        End Sub

        Overridable Sub GetObjectData(
         info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData

            info.AddValue("baseValue", baseValue)

        End Sub
    End Class

End Namespace
// [SerializableAttribute]
public class BaseType : ISerializable
{
    int baseValue;

    public BaseType()
    {
        baseValue = 3;
    }

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

    public virtual void GetObjectData(
       SerializationInfo info, StreamingContext context)
    {
        info.AddValue("baseValue", baseValue);
    }
}