NonSerialized members serialized with XmlSerializer

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???
 
S

Scott Bonds

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top