V3097. Possible exception: type marked by [Serializable] contains non-serializable members not marked by [NonSerialized].
The analyzer detected a suspicious class marked with the [Serializable] attribute and containing members of non-serializable types (i.e. types that are themselves not marked with this attribute). At the same time, these members are not marked with the [NonSerialized] attribute. The presence of such members may lead to raising a 'SerializationException' for some standard classes when attempting to serialize an instance of such a class.
Consider the following example. Suppose we have declared a method to handle object serialization and deserialization:
static void Foo(MemoryStream ms, BinaryFormatter bf, C1 obj)
{
bf.Serialize(ms, obj);
ms.Position = 0;
obj = (C1)bf.Deserialize(ms);
}
We have also declared classes 'C1' and 'NonSerializedClass':
sealed class NonSerializedClass { }
[Serializable]
class C1
{
private Int32 field1;
private NotSerializedClass field2;
}
When attempting to serialize an instance of the 'C1' class, a 'SerializationException' will be thrown, as marking a class with the [Serializable] attribute implies that all of its fields are to be serialized while the type of the 'field2' field is not serializable, which will result in raising the exception. To resolve this issue, the 'field2' field must be decorated with the [NonSerialized] attribute. A correct declaration of the 'C1' class will then look like this:
[Serializable]
class C1
{
private Int32 field1;
[NonSerialized]
private NotSerializedClass field2;
}
Properties are handled a bit differently. Consider the following example:
[Serializable]
class C2
{
private Int32 field1;
public NonSerializedClass Prop { get; set; }
}
You cannot apply the [NonSerialized] attribute to properties. Nevertheless, the exception will be thrown anyway when attempting to serialize a class like the one in the code above using, for example, 'BinaryFormatter'. The reason is that the compiler expands auto-implemented properties into a field and corresponding "get" and possibly "set" accessors. What will be serialized in this case is not the property itself but the field generated by the compiler. This issue is similar to the one with field serialization discussed above.
The error can be fixed by explicitly implementing the property through some field. A correct version of the code will then look like this:
[Serializable]
class C2
{
private Int32 field1;
[NonSerialized]
private NonSerializedClass nsField;
public NonSerializedClass Prop
{
get { return nsField; }
set { nsField = value; }
}
}
You can look at examples of errors detected by the V3097 diagnostic. |