Wednesday, November 20, 2013

read only property and XmlSerializer

I had an issue serializing a class using the XmlSerializer, where the class had a collection property.

example:

public List<Employee> Subordinates { getprivate set; } 

if the property setter was public then everything works fine and the property serialized .
but if the property has a private setter then the following exception is thrown

Unable to generate a temporary class (result=1). error CS0200: Property or indexer '[namespace].Subordinates' cannot be assigned to -- it is read only

The problem was that the class exposed the collection property as a readonly property, but the XmlSerializer needs the property to be read/write access

so the solution is to make the property with public setter as follows
public List<Employee> Subordinates { getset; }