Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't [NonSerialized] work on autoimplemented properties?

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

Why is this disallowed?

I know about the workarounds such as

  • implementing ISerializable
  • switching to XmlSerializer/XmlIgnore
  • switching to a manually-implemented property

The question is specifically why is [NonSerialized] disallowed on properies, yet allowed on fields.

like image 295
Stefan Monov Avatar asked Sep 21 '10 13:09

Stefan Monov


2 Answers

Properties are actually methods, they are not serialized by the binary serialization process. It's the fields that are serialized. So it only makes sense to specify NonSerialized on a field.

like image 154
Thomas Levesque Avatar answered Sep 29 '22 07:09

Thomas Levesque


I think this is a case of fine-grained control requiring more effort on your part. In other words, an automatic property will by default have a serializable backing field. If you want anything other than the default, then you can't use an automatic property.

I had thought that using [field:NonSerialized] against the property might work, but it does not. The C# spec does not explicitly call out the serializability of the backing field, but it does include 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 backing field is serializable (the default).

like image 24
Kent Boogaart Avatar answered Sep 29 '22 08:09

Kent Boogaart