Skip to content

Gendarme.Rules.Serialization.ImplementISerializableCorrectlyRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

ImplementISerializableCorrectlyRule

Assembly: Gendarme.Rules.Serialization
Version: git

Description

This rule checks for types that implement ISerializable. Such types serialize their data by implementing GetObjectData. This rule verifies that every instance field, not decorated with the NonSerialized attribute is serialized by the GetObjectData method. This rule will also warn if the type is unsealed and the GetObjectData is not virtual.

Examples

Bad example:

[Serializable]
public class Bad : ISerializable {
    int foo;
    string bar;
    protected Bad (SerializationInfo info, StreamingContext context)
    {
        foo = info.GetInt32 ("foo");
    }
    // extensibility is limited since GetObjectData is not virtual:
    // any type inheriting won't be able to serialized additional fields
    public void GetObjectData (SerializationInfo info, StreamingContext context)
    {
        info.AddValue ("foo", foo);
        // 'bar' is not serialized, if not needed then the field should
        // be decorated with [NotSerialized]
    }
}

Good example (virtual and not serialized):

[Serializable]
public class Good : ISerializable {
    int foo;
    [NotSerialized]
    string bar;
    protected Good (SerializationInfo info, StreamingContext context)
    {
        foo = info.GetInt32 ("foo");
    }
    public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
    {
        info.AddValue ("foo", foo);
    }
}

Good example (sealed type and serialized):

[Serializable]
public sealed class Good : ISerializable {
    int foo;
    string bar;
    protected Good (SerializationInfo info, StreamingContext context)
    {
        foo = info.GetInt32 ("foo");
    }
    public void GetObjectData (SerializationInfo info, StreamingContext context)
    {
        info.AddValue ("foo", foo);
        info.AddValue ("bar", bar);
    }
}

Notes

  • This rule is available since Gendarme 2.0

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally