Skip to content

Gendarme.Rules.Serialization.DeserializeOptionalFieldRule(git)

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

DeserializeOptionalFieldRule

Assembly: Gendarme.Rules.Serialization
Version: git

Description

This rule will fire if a type has fields marked with OptionalField, but does not have methods decorated with the OnDeserialized or OnDeserializing attributes. This is a problem because the binary deserializer does not actually construct objects (it uses System.Runtime.Serialization.FormatterServices.GetUninitializedObject instead). So, if binary deserialization is used the optional field(s) will be zeroed instead of properly initialized. This rule only applies to assemblies compiled with the .NET framework version 2.0 (or later).

Examples

Bad example:

[Serializable]
public class ClassWithOptionalField {
    [OptionalField]
    private int optional;
}

Good example:

[Serializable]
public class ClassWithOptionalField {
    // Normally the (compiler generated) default constructor will
    // initialize this. The default constructor will be called by the
    // XML and Soap deserializers, but not the binary serializer.
    [OptionalField]
    private int optional = 1;
    // This will be called immediately after the object is
    // deserialized.
    [OnDeserializing]
    private void OnDeserializing (StreamingContext context)
    {
        optional = 1;
    }
}

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