Skip to content
Legacy .NET serialization Reviewed 2026-09-13

Serialization Event Implement

What does this mean ?

Serializers that support System.Runtime.Serialization callback attributes expect specific method signatures. For an OnDeserialized callback, use a non-generic instance method returning void with one StreamingContext parameter. Keep implementation callbacks private. Microsoft's callback documentation describes this contract.

What can happen ?

An unsupported signature may cause serialization to fail. An unsupported attribute may have no effect with a different serializer. It is inaccurate to claim that every public callback is always ignored or that an attribute guarantees validation runs. This is a reliability and data-invariant concern; security impact depends on what later code trusts.

Recommendation

Check the actual serializer's lifecycle and prefer explicit validation after parsing at the application boundary. System.Text.Json does not use these legacy attributes; supported versions provide JSON-specific callback interfaces such as IJsonOnDeserialized. Neither mechanism makes BinaryFormatter safe for untrusted data.

Sample Code

These alternative fragments belong to a DataContractSerializer model whose Count member is marked [DataMember].

Incorrect callback signature:

[OnDeserialized]
private void AfterRead()
{
    if (Count < 0) throw new SerializationException("Invalid count");
}

Correct callback signature for this serializer:

[OnDeserialized]
private void AfterRead(StreamingContext context)
{
    if (Count < 0) throw new SerializationException("Invalid count");
}

Regression test: deserialize a benign fixture with Count = 2 and confirm success; deserialize a fixture with Count = -1 and confirm failure. Repeat when changing serializers. An attribute/reflection check alone cannot demonstrate that the chosen serializer invokes the callback.

References