XmlSerializer and automatic collection properties

August 7, 2009 at 2:09 PMAndre Loker

I noticed an interesting detail in the way XmlSerializer handles collection properties. FxCop rule CA2227 suggest to make collection properties read-only, because XmlSerializer is treating collections differently as described here (scroll down to the “Note” box under “Overriding Default Serialization”). When I tried to serialize the following class, however, I got an error during serialization:

   1: public class SomeClass
   2: {
   3:   public SomeClass()
   4:   {
   5:     CollectionProperty = new List<int>();
   6:   }
   7:  
   8:   public List<int> CollectionProperty { get; private set; }
   9: }

The error was something like:

System.InvalidOperationException: Unable to generate a temporary class (result=1).

error CS0200: Property or indexer 'SomeClass.CollectionProperty' cannot be assigned to — it is read only.

Erm, right, I made it read-only because FxCop suggested it, so what’s wrong here? The answer is that “making the collection property read-only” should be read as “don’t provide a setter of any visibility”, because technically a property with a private setter is still writable, albeit from within the class only, leading to the runtime error as described above. FxCop on the other hand will stop complaining as soon as the setter is made private. 

As soon as I changed the automatic property to a property with backing field without a setter the application ran fine:

   1: public class SomeClass
   2: {
   3:   private readonly List<int> collectionProperty;
   4:  
   5:   public SomeClass()
   6:   {
   7:     collectionProperty = new List<int>();
   8:   }
   9:  
  10:   public List<int> CollectionProperty
  11:   {
  12:     get { return collectionProperty; }
  13:   }
  14: }

Posted in: C#

Tags: , ,