I'm going through a lot of code and marking classes which I now want to persist with the Serialization attribute. I haven't written the binary serialization/deserization engine as yet so guess I will answer my own question once that's complete! - but thought I'd try get an earlier response here if that's OK. I've come across some code which contains a property such as:
public string Id
{
get;
set;
}
Does the "Id" get serialized? I understand that underneath the compiler auto creates a class member, but does this get serialized correctly (since all the data members of the class instance are written to storage)? It feels like it won't since you can't place the Serialized/NonSerialized attribute on properties.
Thanks in advance.
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.
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 .
Basic and custom serialization Binary and XML serialization can be performed in two ways, basic and custom.
For example, you can share an object between different applications by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.
You can use the [field:NonSerialized]
attribute to mark the backing field of events as being non-serializable, however it seems this is not possible with auto-properties. With auto-properties the backing fields will be serialized and the only way to prevent that behaviour is to transform them into regular properties and annotate the explicit backing fields with [NonSerialized]
as normal.
As @John has pointed out in his comments, the BinaryFormatter
(System.Runtime.Serialization.Formatters.Binary
) will serialize your auto-generated backing field. You can use custom serialization by implementing the ISerializable
interface and then decide for your class which values are serialized or not.
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