How to implement GetObjectData in object with ISerializable field that itself has custom serialization?

598 Views Asked by At

What is the correct way to implement ISerializable interface for the class that has ISerializable field?

Assume I have the following two classes, and I have to implement custom serialization for both of them. How should I implement the serialization/deserialization of Foo?

public class Foo : ISerializable
{
    private int b;

    private Bar bar;

    protected Foo(SerializationInfo info, StreamingContext context)
    {
        b = info.GetInt32("b") + 1000;
        // How should I instantiate "bar" field here?
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("b", b - 1000);
        // How should I serialize "bar" field here?
    }
}

public class Bar : ISerializable
{
    private int a;

    public Bar(SerializationInfo info, StreamingContext context)
    {
        a = info.GetInt32("a") + 100;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("a", a - 100);
    }
}
0

There are 0 best solutions below