Skip to content

Serialization Event Implement

Serialization event handlers must be properly implemented.

What does this mean ?

Serialization event handlers must be properly implemented. Serialization event handlers that do not have the right signature will be ignored, thereby circumventing any attempts to supplement the automatic de-serialization.

What can happen ?

When a method tagged with one of the following qualities is public, static, does not return void, contains type arguments, or does not have a single parameter of type, this rule raises an issue System.Runtime.Serialization.StreamingContext:

  • System.Runtime.Serialization.OnSerializingAttribute
  • System.Runtime.Serialization.OnSerializedAttribute
  • System.Runtime.Serialization.OnDeserializingAttribute
  • System.Runtime.Serialization.OnDeserializedAttribute

Sample Code

Vulnerable :

[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
}

Non Vulnerable :

[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) {}
}

References