org.sonar.plugins.csharp.S3927.html Maven / Gradle / Ivy
Why is this an issue?
Serialization event handlers that don’t have the correct signature will not be called, bypassing augmentations to automated serialization and
deserialization events.
A method is designated a serialization event handler by applying one of the following serialization event attributes:
Serialization event handlers take a single parameter of type StreamingContext
, return
void
, and have private
visibility.
This rule raises an issue when any of these constraints are not respected.
How to fix it
Code examples
Noncompliant code example
[Serializable]
public class Foo
{
[OnSerializing]
public void OnSerializing(StreamingContext context) {} // Noncompliant: should be private
[OnSerialized]
int OnSerialized(StreamingContext context) {} // Noncompliant: should return void
[OnDeserializing]
void OnDeserializing() {} // Noncompliant: should have a single parameter of type StreamingContext
[OnSerializing]
public void OnSerializing2<T>(StreamingContext context) {} // Noncompliant: should have no type parameters
[OnDeserialized]
void OnDeserialized(StreamingContext context, string str) {} // Noncompliant: should have a single parameter of type StreamingContext
}
Compliant solution
[Serializable]
public class Foo
{
[OnSerializing]
private void OnSerializing(StreamingContext context) {}
[OnSerialized]
private void OnSerialized(StreamingContext context) {}
[OnDeserializing]
private void OnDeserializing(StreamingContext context) {}
[OnDeserialized]
private void OnDeserialized(StreamingContext context) {}
}
Resources
Documentation
- Microsoft Learn - CA2238: Implement serialization methods
correctly
© 2015 - 2024 Weber Informatics LLC | Privacy Policy