How to prevent auto implemented properties from being serialized?

hopla picture hopla · Nov 13, 2009 · Viewed 20.8k times · Source

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.

Answer

Jehof picture Jehof · Nov 13, 2009

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; }
  }
}