Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto implemented properties and serialization

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.

like image 741
Jeb Avatar asked Feb 02 '12 15:02

Jeb


People also ask

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 are auto 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 .

What are the types of serialization?

Basic and custom serialization Binary and XML serialization can be performed in two ways, basic and custom.

What is serialization in .NET with example?

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.


2 Answers

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.

like image 134
Paul Ruane Avatar answered Sep 21 '22 23:09

Paul Ruane


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.

like image 31
Mithrandir Avatar answered Sep 24 '22 23:09

Mithrandir