Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set The "NonSerializedAttribute" To An Auto Property

Tags:

c#

This cannot be done in C#. Any way to do it?

...

laugh, in case my little pun wasn't understood, what I mean is: how can I mark a property in C# as NonSerialized? Of course, when the property contains logic, it's natural to be unable to do it, but Auto-Properties are serializable, and, as such, I would expect to have some way to allow me to prevent their serialization.

like image 550
Axonn Avatar asked Nov 15 '10 13:11

Axonn


People also ask

What does non serialized mean?

Serialized inventory models have individual serial units, each of which have their own unique barcode. Non-serialized inventory models do not have individually barcoded units. Detailed examples of both serialized and non-serialized models are shown below.

What is the point of auto properties?

properties allow your access to be polymorphic (inheritors can modify access if the property is virtual) if you so choose. auto-properties are nice when you're dealing with simple get/set operations. if you do more complicated operations inside your get / set, then you can't use the auto-property.

How to not serialize a property in c#?

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. For example, you can use this attribute to prevent the serialization of sensitive data.

What is serializable attribute in C#?

This attribute is used in the class definition to indicate that a class can be serialized. By default, all fields in the class are serialized except for the fields that are marked with a NonSerializedAttribute . It is not necessary to use this attribute if a given type implements the System.


1 Answers

  [NonSerialized]
  public string MyProperty { get; set; }

Is an error

  [XmlIgnore]
  public string MyProperty { get; set; }

Is not an error

NonSerialized Indicates that a field of a serializable class should not be serialized.

XmlIgnore Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value

so, if you ask

I would expect to have some way to allow me to prevent their serialization.

the answer yes, if you're using XmlSerializer

like image 177
Emanuele Greco Avatar answered Nov 10 '22 09:11

Emanuele Greco