C#idiomatic C#
ca2229fundamentals/code-analysis/quality-rules

Code analysis

CA2229: Implement serialization constructors

Learn about code analysis rule CA2229: Implement serialization constructors

CA2229 Usage enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

The type implements the System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, and one of the following conditions is true:

Rule description

This rule is relevant for types that support custom serialization. A type supports custom serialization if it implements the System.Runtime.Serialization.ISerializable interface. The serialization constructor is required to deserialize, or recreate, objects that have been serialized using the System.Runtime.Serialization.ISerializable.GetObjectData method.

How to fix violations

To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected.

When to suppress warnings

Do not suppress a violation of the rule. The type will not be deserializable, and will not function in many scenarios.

Example

The following example shows a type that satisfies the rule.

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2229.cssnippet1

csharp
using System;
using System.Runtime.Serialization;

namespace ca2229
{
    //<snippet1>
    [Serializable]
    public class SerializationConstructorsRequired : ISerializable
    {
        private int n1;

        // This is a regular constructor.
        public SerializationConstructorsRequired()
        {
            n1 = -1;
        }
        // This is the serialization constructor.
        // Satisfies rule: ImplementSerializationConstructors.

        protected SerializationConstructorsRequired(
           SerializationInfo info,
           StreamingContext context)
        {
            n1 = (info.GetValue(nameof(n1), typeof(int)) != null) ?
                (int)info.GetValue(nameof(n1), typeof(int))! :
                -1;
        }

        // The following method serializes the instance.
        void ISerializable.GetObjectData(SerializationInfo info,
           StreamingContext context)
        {
            info.AddValue(nameof(n1), n1);
        }
    }
    //</snippet1>
}

CA2237: Mark ISerializable types with SerializableAttribute

See also