Search code examples
c#serializationautomatic-properties

How to prevent auto implemented properties from being serialized?


How can I prevent a auto implemented property from being serialized by the binary formatter? The [NonSerialized] attribute can only be used with fields. And the field is hidden when using auto implemented properties.


Solution

  • It´s not supported for auto implemented properties. You have to use a backing field and set the NonSerializedAttribute on it.

    public class ClassWithNonSerializedProperty {
    
      [NonSerialized]
      private object _data;  // Backing field of Property Data that is not serialized
    
      public object Data{
        get { return _data; }
        set { _data = value; }
      }
    }