The ISerializable interface is
the mechanism to control the type serialization process. If not implemented correctly this could result in an invalid serialization and hard-to-detect
bugs.
This rule raises an issue on types that implement ISerializable without following the serialization pattern recommended by Microsoft.
Specifically, this rule checks for these problems:
- The
SerializableAttribute attribute is
missing.
- Non-serializable fields are not marked with the
NonSerializedAttribute attribute.
- There is no serialization constructor.
- An unsealed type has a serialization constructor that is not
protected.
- A sealed type has a serialization constructor that is not
private.
- An unsealed type has an
ISerializable.GetObjectData that is not both public and virtual.
- A derived type has a serialization constructor that does not call the
base constructor.
- A derived type has an
ISerializable.GetObjectData method that does not call the base method.
- A derived type has serializable fields but the
ISerializable.GetObjectData method is not overridden.
Classes that inherit from Exception are implementing
ISerializable. Make sure the [Serializable] attribute is used and that ISerializable is correctly implemented.
Even if you don’t plan to explicitly serialize the object yourself, it might still require serialization, for instance when crossing the boundary of
an AppDomain.
This rule only raises an issue on classes that indicate that they are interested in serialization (see the Exceptions section). That is to
reduce noise because a lot of classes in the base class library are implementing ISerializable, including the following classes: Exception, Uri, Hashtable, Dictionary<TKey,TValue>, DataSet, HttpWebRequest, Regex TreeNode, and others. There is often no need to add
serialization support in classes derived from these types.
Exceptions
- Classes in test projects are not checked.
- Classes need to indicate that they are interested in serialization support by either
- Applying the
[Serializable] attribute
- Having
ISerializable in their base type list
- Declaring a serialization
constructor
[Serializable] // 1.
public class SerializationOptIn_Attribute
{
}
public class SerializationOptIn_Interface : ISerializable // 2.
{
}
public class SerializationOptIn_Constructor
{
protected SerializationOptIn_Constructor(SerializationInfo info, StreamingContext context) // 3.
{
}
}