[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.
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
NonSerializedon a field.