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.
Try marking the field with [NonSerialized()] attribute. This will tell the serializer to ignore the field.
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.
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.
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 .
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; }
}
}
// 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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With