NonSerialized members serialized with XmlSerializer

  • Thread starter Thread starter Steve Bloomfield
  • Start date Start date
S

Steve Bloomfield

If I use a SoapFormatter or BinaryFormatter, any member variables
marked [NonSerialized] are ignored. But if I use the XmlSerializer,
it tries to serialize them. In some cases this throws an exception
because the object type is not serializable. Try this sample code:

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

namespace testserial
{
[Serializable]
public class MyObject
{
public int n1 = 0;
[NonSerialized] public int n2 = 1;
public String str = null;
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.n1 = 1;
//obj.n2 = 24;
obj.str = "Some String";
XmlSerializer formatter = new XmlSerializer(typeof(MyObject));
// SoapFormatter formatter = new SoapFormatter();
Stream stream = new FileStream("c:\\MyFile.xml",
FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

}
}
}

Run it and you will see n2 written to the file. Comment the
XmlSerializer line and uncomment the SoapFormatter line and run it, n2
is not written to the file.

Is this a bug or working as designed???
 
Steve Bloomfield said:
If I use a SoapFormatter or BinaryFormatter, any member variables
marked [NonSerialized] are ignored. But if I use the XmlSerializer,
it tries to serialize them. In some cases this throws an exception
because the object type is not serializable. Try this sample code:

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

namespace testserial
{
[Serializable]
public class MyObject
{
public int n1 = 0;
[NonSerialized] public int n2 = 1;
public String str = null;
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.n1 = 1;
//obj.n2 = 24;
obj.str = "Some String";
XmlSerializer formatter = new XmlSerializer(typeof(MyObject));
// SoapFormatter formatter = new SoapFormatter();
Stream stream = new FileStream("c:\\MyFile.xml",
FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

}
}
}

Run it and you will see n2 written to the file. Comment the
XmlSerializer line and uncomment the SoapFormatter line and run it, n2
is not written to the file.

Is this a bug or working as designed???

I don't know, but I can confirm this behaviour and it sure seems like a bug
to me. Have you heard anything from MS about it?

sb
 
Back
Top