2

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);
    }
}
Eduard Grinberg
  • 129
  • 2
  • 8
  • Did you look at the source code? https://referencesource.microsoft.com/#mscorlib/system/runtime/serialization/serializationinfo.cs,4ade46c59f4e07b4 – jdweng Jan 10 '19 at 12:02
  • @jdweng, I did now, but I don't understand what should I find there? My question is: how do I correctly invoke GetObjectData of the bar field? Or should I just add it as is to the SerializationInfo? – Eduard Grinberg Jan 10 '19 at 12:39
  • bar = (Bar)info.GetValue("bar",typeof(Bar)); and info.AddValue("bar", bar); – jdweng Jan 10 '19 at 12:57
  • @jdweng, thanks for you answer. I tried what you suggested and when trying to serialize the object, I receive the exception:Type 'ConsoleApplication1.Bar' with data contract name 'Bar:http://schemas.datacontract.org/2004/07/ConsoleApplication1' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer. Am I missing something? – Eduard Grinberg Jan 10 '19 at 20:25
  • Are you serializing or deserializing. I usually try to serialize first and then take the serialize data and deserialize. – jdweng Jan 10 '19 at 23:14
  • @jdweng, actually now I saw, it works with BinaryFormatter which is good. I would like it to be part of WCF Rest api and thus I used DataContractSerializer to test and had the above problem with it during serialization. – Eduard Grinberg Jan 13 '19 at 11:35
  • Why use DataContractSerializer? Just save the binaryserializer results to the database as a byte[]. – jdweng Jan 13 '19 at 12:04
  • @jdweng, I need to accept Foo as a parameter in WCF. But this, might be a separate topic. – Eduard Grinberg Jan 13 '19 at 13:12

0 Answers0