I am trying to serialize an object that has a nested class. I have tagged the nested class with the [NonSerialized] attribute but I receive an error:
Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations.
How do I omit the nested class from serialization?
I have included some code that may show what I am trying to do. Thanks for any help.
[Serializable]
public class A_Class
{
public String text { get; set; }
public int number { get; set; }
}
[Serializable]
public class B_Class
{
[NonSerialized]
public A_Class A { get; set; }
public int ID { get; set; }
}
public byte[] ObjectToByteArray(object _Object)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, _Object);
return stream.ToArray();
}
}
void Main()
{
Class_B obj = new Class_B()
byte[] data = ObjectToByteArray(obj);
}