6

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);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Brad
  • 20,302
  • 36
  • 84
  • 102
  • 1
    The error is fully describes the problem - you cannot apply this attribute to anything except fields (you're trying to apply it to a property). – Oleks Mar 29 '11 at 15:18

3 Answers3

11

The error tells you everything you need to know: NonSerialized can only be applied to fields, but you are trying to apply it to a property, albeit an auto-property.

The only real option you have is to not use an auto property for that field as noted in this StackOverflow question.

Community
  • 1
  • 1
DocMax
  • 12,094
  • 7
  • 44
  • 44
10

Also consider XmlIgnore attribute on the property:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

IIRC, properties are ignored automatically for binary serialization.

Aeonymous
  • 101
  • 2
7

Try explicitly using a backing field which you can mark as [NonSerialized]

[Serializable]
public class B_Class
{
  [NonSerialized]
  private A_Class a;  // backing field for your property, which can have the NonSerialized attribute.
  public int ID { get; set; }

  public A_Class A // property, which now doesn't need the NonSerialized attribute.
  {
    get { return a;}
    set { a= value; }
  }
}

The problem is that the NonSerialized attribute is valid on fields but not properties, therefore you can't use it in combination with auto-implemented properties.

Rob Levine
  • 40,328
  • 13
  • 85
  • 111