>
>
>
V3099. Not all the members of type are …


V3099. Not all the members of type are serialized inside 'GetObjectData' method.

The analyzer detected a suspicious implementation of method 'GetObjectData', where some of the serializable type members are left unserialized. This error may result in incorrect object deserialization or raising a 'SerializationException'.

Consider the following example. Suppose we have declared a method to handle object serialization and deserialization.

static void Foo(BinaryFormatter bf, MemoryStream ms, Derived obj)
{
  bf.Serialize(ms, obj);
  ms.Position = 0;
  obj = (Derived)bf.Deserialize(ms);
}

Declaration of class 'Base':

abstract class Base
{
  public Int32 Prop { get; set; }
}

Declaration of class 'Derived':

[Serializable]
sealed class Derived : Base, ISerializable
{
  public String StrProp { get; set; }

  public Derived() { }

  private Derived(SerializationInfo info, 
                  StreamingContext context)
  {
    StrProp = info.GetString(nameof(StrProp));
  }

  public void GetObjectData(SerializationInfo info, 
                            StreamingContext context)
  {
    info.AddValue(nameof(StrProp), StrProp);
  }
}

When declaring the 'Derived' class, the programmer forgot to serialize the 'Prop' property of the base class, which will result in incomplete saving of the object's state when it is serialized. When the object is deserialized, the 'Prop' property will be set to the default value, which is 0 in this case.

To ensure that the object's state is saved in full during serialization, we need to modify the code by specifying in the implementation of method 'GetObjectData' that the 'Prop' property's value should be stored in an object of type 'SerializationInfo', and in the serialization constructor that it should retrieve that value.

The fixed implementation of method 'GetObjectData' and 'Derived' class' serialization constructor should look like this:

private Derived(SerializationInfo info, 
                StreamingContext context)
{
  StrProp = info.GetString(nameof(StrProp));
  Prop = info.GetInt32(nameof(Prop));
}

public void GetObjectData(SerializationInfo info, 
                          StreamingContext context)
{
  info.AddValue(nameof(StrProp), StrProp);
  info.AddValue(nameof(Prop), Prop);
}

In the example that we've discussed above, the developer of the base class didn't cater for its serialization. If there is enabled and the type implements the 'ISerializable' interface, then for the correct serialization of the members of the base class we should call the method 'GetObjectData' of the base class from the derived one:

public override void GetObjectData(SerializationInfo info, 
                                   StreamingContext context)
{
  base.GetObjectData(info, context);
  ....
}

Additional information:

This diagnostic is classified as: