From: Arne Vajhøj on
On 16-04-2010 10:10, Julie wrote:
> I've been looking over serialization and am slightly confused... Is the
> SerializableAttribute required above the class when using XML
> serialization?

No.

> If not, why not? If so, why so?

Real serialization (binary serialization) and XML serialization
actually works very differently.

Look at the following program:

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

namespace E
{
[Serializable]
public class Data
{
private int v1;
private int v2;
public Data()
{
v1 = 1;
v2 = 2;
}
public void IncV1()
{
v1++;
}
public int V2 { get { return v2; } set { v2 = value; } }
public override string ToString()
{
return "(" + v1 + "," + v2 + ")";
}
}
public class Program
{
public static void Main(string[] args)
{
Data o = new Data();
o.IncV1();
o.V2 = 3;
Console.WriteLine(o);
XmlSerializer ser = new XmlSerializer(typeof(Data));
StreamWriter sw = new StreamWriter(@"C:\data.xml");
ser.Serialize(sw, o);
sw.Close();
StreamReader sr = new StreamReader(@"C:\data.xml");
Data ox = (Data)ser.Deserialize(sr);
sr.Close();
Console.WriteLine(ox);
BinaryFormatter bf = new BinaryFormatter();
FileStream outf = File.Create(@"C:\data.bin");
bf.Serialize(outf, o);
outf.Close();
FileStream inf = File.OpenRead(@"C:\data.bin");
Data ob = (Data)bf.Deserialize(inf);
inf.Close();
Console.WriteLine(ob);
Console.ReadKey();
}
}
}

It outputs:

(2,3)
(1,3)
(2,3)

The real/binary serialization is a feature built deep into the CLR. It
needs the attribute as verification that it can do its job.

The XML serialization is a mucg higher level thing. I assume that
it uses simple reflection. It does not need the attribute. Public
properties is a good enough verification.

BTW, it is the same thing in Java.

Arne