Rule Definition
The OptionalFieldAttribute attribute has no effect on serialization; a field marked with the attribute is serialized. However, the field is ignored on de-serialization and retains the default value associated with its type. De-serialization event handlers should be declared to set the field during the de-serialization process
Remediation
Add [OnDeserialized] OR [OnDeserializing] event handlers to the type
Violation Code Sample
namespace UsageLibrary
{
[SerializableAttribute]
public class SerializationEventHandlers
{
[OptionalFieldAttribute(VersionAdded = 2)]
int optionalField = 5;
} }
Fixed Code Sample
namespace UsageLibrary
{
[SerializableAttribute]
public class SerializationEventHandlers
{
[OptionalFieldAttribute(VersionAdded = 2)]
int optionalField = 5;
[OnDeserializingAttribute]
void OnDeserializing(StreamingContext context)
{
optionalField = 5;
}
[OnDeserializedAttribute]
void OnDeserialized(StreamingContext context)
{
// Set optionalField if dependent on other deserialized values.
}
}
}
Reference
https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2239?view=vs-2019
Related Technologies
Technical Criterion
Secure Coding - Weak Security Features
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.