CA2229: Implement serialization constructors
The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.
The latest version of this topic can be found at CA2229: Implement serialization constructors.
TypeName|ImplementSerializationConstructors|
|CheckId|CA2229|
|Category|Microsoft.Usage|
|Breaking Change|Non Breaking|
The type implements the System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, and one of the following conditions is true:
The type does not have a constructor that takes a System.Runtime.Serialization.SerializationInfo object and a System.Runtime.Serialization.StreamingContext object (the signature of the serialization constructor).
The type is unsealed and the access modifier for its serialization constructor is not protected (family).
The type is sealed and the access modifier for its serialization constructor is not private.
This rule is relevant for types that support custom serialization. A type supports custom serialization if it implements the ISerializable interface. The serialization constructor is required to deserialize, or re-create objects that have been serialized using the ISerializable.GetObjectData method.
To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected.
Do not suppress a violation of the rule. The type will not be deserializable, and will not function in many scenarios.
The following example shows a type that satisfies the rule.
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Permissions; namespace UsageLibrary { [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 = (int) info.GetValue("n1", typeof(int)); } // The following method serializes the instance. [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("n1", n1); } } }
CA2237: Mark ISerializable types with SerializableAttribute
System.Runtime.Serialization.ISerializable
System.Runtime.Serialization.SerializationInfo
System.Runtime.Serialization.StreamingContext