views:

462

answers:

5

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.

A: 

If you are serializing to Xml then you can use XmlIgnore attribute.

Danil
As I noted, we are using the binary formatter...
hopla
+3  A: 

I'm not sure you can. This MSDN article on SerializableAttribute suggests you implement ISerializable and control the serialisation yourself:

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process.

Or switch away from an auto-property for that specific field.

Neil Barnwell
+7  A: 

It´s not supported for auto implemented properties. You have to use a backing field and set the attribte [NonSerialized] 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; }
  }
}
Jehof
You are right. I'm afraid we'll have to go down this route here...
hopla
+3  A: 
// This works for the underlying delegate of the `event` add/remove mechanism.
[field:NonSerialized]
public event EventHandler SomethingHappened;

But it doesn't seem to for auto-implemented properties. I thought it was worth mentioning because it's useful to know when serializing an object with event subscribers attached to it.

frou
+1  A: 

It's not possible for auto implemented properties. Consider folowing:

This behavior is "by design". The decision at the time auto-properties were implemented was that they would work in the "common case" which among other things means no attributes on the generated field. The idea behind that is keeping them simple and not slowly mutating them into full properties. So, if you need to use the NonSerialized attribute full properties are the way.

(http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/2b6eb489-122a-4418-8759-10808252b195)

Sergey Teplyakov