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?
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.
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.
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.
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.
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.
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