Why is [NonSerialized] not working on auto-implemented properties?

[Serializable] class MyClass { [NonSerialized] int Foo { get; set; } // error [NonSerialized] int bar; // ok } 

Why is it forbidden?

I know about workarounds like

  • implementation of ISerializable
  • transition to XmlSerializer / XmlIgnore
  • transition to a manually implemented property

The question is why [NonSerialized] is forbidden by properties, but allowed for fields.

+6
serialization
source share
3 answers

Properties are actually methods; they are not serialized during binary serialization. These are fields that are serialized. Therefore, it makes sense to specify NonSerialized in the field.

+12
source share

I think this is a case of fine-grained control that requires more effort on your part. In other words, the automatic property will have a serializable support field by default. If you want nothing but the default, then you cannot use the automatic property.

I thought using [field:NonSerialized] against a property might work, but it is not. The C # specification does not explicitly cause the support field to be serializable, but it includes this (10.7.3):

 The following example: public class Point { public int X { get; set; } // automatically implemented public int Y { get; set; } // automatically implemented } is equivalent to the following declaration: public class Point { private int x; private int y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } 

Thus, the support field is serializable (default).

+3
source share

You can look at IgnoreDataMemberAttribute if you use WCF. This works with auto properties.

Works even if you don't mark all the other members as a DataMember (which I always find a pain), but a class with a DataContract

0
source share

All Articles