C# – Why are properties without a setter not serialized

cnetxml-serialization

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?

Best Answer

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.

Related Topic