org.sonar.plugins.csharp.S3926.html Maven / Gradle / Ivy
Why is this an issue?
Fields marked with System.Runtime.Serialization.OptionalFieldAttribute
are serialized just like any other field. But such fields are
ignored on deserialization, and retain the default values associated with their types. Therefore, deserialization event handlers should be declared to
set such fields during the deserialization process.
This rule raises when at least one field with the System.Runtime.Serialization.OptionalFieldAttribute
attribute is declared but one
(or both) of the following event handlers System.Runtime.Serialization.OnDeserializingAttribute
or
System.Runtime.Serialization.OnDeserializedAttribute
are not present.
Noncompliant code example
[Serializable]
public class Foo
{
[OptionalField(VersionAdded = 2)]
int optionalField = 5;
}
Compliant solution
[Serializable]
public class Foo
{
[OptionalField(VersionAdded = 2)]
int optionalField = 5;
[OnDeserializing]
void OnDeserializing(StreamingContext context)
{
optionalField = 5;
}
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
// Set optionalField if dependent on other deserialized values.
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy