[Mono-list] serialization

Jacob Sherman jakesher@edevcentral.com
Wed, 24 Apr 2002 18:46:15 -0700


Classes that implement the IFormatter interface will serialize both private
and public
read/write fields and properties.  So the
System.Runtime.Serialization.FormatterBinaryFormatter
and System.Runtime.Serialization.Soap.SoapFormatter will serialize public
and private fields and
properties.  On the other hand, the System.Xml.Serialization.XmlSerializer
will only serialize
public read/write fields and properties.

using System;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

[Serializable]
public class FooBaz
{
     public int fooooooooooooo = 6;
     private int baaaaaaaaaaaaar = 5;
}

public class SerializationVisibilityTest
{
  public static void Main()
  {
     // will serialize public and private fields/properties
     BinaryFormatter f1 = new BinaryFormatter();
     Stream stream1 = File.Open("footest.bin", FileMode.Create );

     f1.Serialize(stream1, new FooBaz());
     stream1.Close();

     // will serialize public and private fields/properties
     SoapFormatter f2 = new SoapFormatter();
     Stream stream2 = File.Open("footest.soap", FileMode.Create );

     f2.Serialize(stream2, new FooBaz());
     stream2.Close();

     // will only serialize public fields/properties
     XmlSerializer f3 = new XmlSerializer( typeof(FooBaz) );
     Stream stream3 = File.Open("footest.xml", FileMode.Create );

     f3.Serialize(stream3, new FooBaz());
     stream3.Close();
  }
}

I also noticed some interesting but understandable type serialization
behaviour:

// BinaryFormatter ( serializes: NO ), SoapFormatter ( serializes: NO ),
XmlSerializer ( serializes: NO )
public const int fooooooooooooo = 6;
private const int baaaaaaaaaaaaar = 5;

// BinaryFormatter ( serializes: YES ), SoapFormatter ( serializes: YES ),
XmlSerializer ( serializes: NO )
 public readonly int fooooooooooooo = 6;
private readonly int baaaaaaaaaaaaar = 5;

// BinaryFormatter ( serializes: NO ), SoapFormatter ( serializes: NO ),
XmlSerializer ( serializes: NO )
public static int fooooooooooooo = 6;
private static int baaaaaaaaaaaaar = 5;

So...it seems the SoapFormatter, and the BinaryFormatter tend to be more
lenient and the XmlSerializer class
wants 100 percent attribute visibility.