Serialize ignoring NonSerializableAttribute

J

Joe

If I serialize an object from with the same class, any fields with the
NonSerializableAttribute still get serialized but not if I serialize from
outside the class.
Why?

This is a simple case to reproduce the problem. Notice that m_table should
NOT be serialized.

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Test t = new Test();

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.FileStream fs = new
System.IO.FileStream("test_external.txt", System.IO.FileMode.OpenOrCreate);

bf.Serialize(fs, t);

fs.Close();

t.Clone();
}
}

[Serializable]
public class Test : ICloneable
{
[NonSerialized]
private DataTable m_table;

public Test()
{
m_table = new DataTable();
m_table.Columns.Add("Column1");
}


#region ICloneable Members

public object Clone()
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.FileStream fs = new System.IO.FileStream("test.txt",
System.IO.FileMode.OpenOrCreate);

bf.Serialize(fs, this);

fs.Close();

return null;
}

#endregion
}

-Joe
 
J

Joe

OK - it turns out the sample is working but my actual application does
something similar and doesn't work.
 
J

Joe

Never mind. There was a field in the base class the same as in the class
being serialized. The base class field did not have the NonSeriailzed
attribute.
 

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