Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are properties without a setter not serialized

I have a serializable class and one of the properties in my class generates a Guid in the getter. The property implements no setter and is ignores during serialization. Why is that and do I always have to implement a setter in order for my property to be serialized.

[Serializable] public class Example {     [XmlAttribute("id")]     public string Id     {         get         {              return Guid.NewGuid().ToString();         }     } } 

I tried implementing an empty setter and it got serialized correctly.

[Serializable] public class Example {     [XmlAttribute("id")]     public string Id     {         get         {              return Guid.NewGuid().ToString();         }         set {}     } } 

Update:

Can you point out how should I define properties whose values never change or ones that the value for is generated internally?

like image 764
Konstantin Dinev Avatar asked Nov 15 '12 15:11

Konstantin Dinev


People also ask

Are properties serialized unity?

Unfortunately, Unity won't serialize properties directly, but we can serialize the property's backing field. In fact, any private member variable can be serialized by Unity if we annotate it with the SerializeField attribute.

Why do objects need to be serialized?

Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.

What is non serialized attribute in serialization?

The target objects for the NonSerializedAttribute attribute are public and private fields of a serializable class. By default, classes are not serializable unless they are marked with SerializableAttribute. During the serialization process all the public and private fields of a class are serialized by default.

How do I prevent some data from getting serialized?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.


1 Answers

It's a limitation of XmlSerializer it doesn't serialize read-only properties, what you have done in your second example is essentially the hack to get it to serialize, however, it's useless if you need it to deserialize later.

Alternatively you could switch to using DataContractSerializer, it's more flexible.

like image 172
James Avatar answered Sep 28 '22 00:09

James