Difference between BinaryFormatter and SoapFormatter for type handling

Viewed 32

Here is a short code that works fine with BinaryFormatter and does not work properly with SoapFormatter:

       [Serializable]
       public class CustomDictionary : Dictionary<int, object>
       {
           public CustomDictionary() { } 
           protected CustomDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }
       }

        var input = new CustomDictionary();
        input.Add(1, new Address("NYC", "Gold street", 17));
        input.Add(2, "mystring");
        input.Add(3, new Being("Serge"));

        IFormatter formatter = new SoapFormatter(); // works fine with BinaryFormatter() here
        FileStream s = new FileStream("test.data", FileMode.Create);
        formatter.Serialize(s, input);
        s.Close();
        FileStream s2 = new FileStream("test.data", FileMode.Open);
        var output = (CustomDictionary)formatter.Deserialize(s2);
        s2.Close();

Here, Being and Address are serializable classes. I basically want to be able to put any kind of objects as values in my custom dictionary. If I use the SoapFormatter, after deserialization, values at index 1 and 3 are null in output (the recreated custom dictionary). It seems to me that BinaryFormatter stores the type of the objects while the SoapFormatter does not.

Am I missing something?

Is there any way to have the same behaviour with the SoapFormatter than with the BinaryFormatter?

Thank you,

0 Answers
Related