Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
hopla Avatar asked Nov 13 '09 10:11

hopla


People also ask

How do you ignore property serializable?

Try marking the field with [NonSerialized()] attribute. This will tell the serializer to ignore the field.

What are auto-implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

What is an auto-implemented property and what does it automatically create?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is the point of automatic properties in C#?

Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it. We can use attributes in many cases but often we need properties because features in different .


3 Answers

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; }
  }
}
like image 185
Jehof Avatar answered Oct 23 '22 19:10

Jehof


// 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.

like image 7
xyz Avatar answered Oct 23 '22 17:10

xyz


If you're serializing to Json and using the Json.NET serializer (which I'd highly recommend as it has a lot more to offer than a number of other serializers on the market) then you can achieve your desired outcome on properties using [JsonIgnore].

You don't need to create a field.

So your code would be:

public class ClassName
{
     [JsonIgnore]   
     public object IgnoreMe { get; set; } 

     public object DoNotIgnoreMe { get; set; } 
}
like image 6
Bern Avatar answered Oct 23 '22 17:10

Bern