1

I have some types I want to serialize as xml, but these types have read-only properties like:

public List<Effect> Effects {get; private set;}

but the xml serializer requires these properties to be writable.

  1. Isn't xml serializer using reflection, so in effect can easily set these properties via reflection even though they are read-only?

  2. Is there a way around this because I don't want these types to be editable by people, so the properties must be read-only, but I also want them to be xml serializeable.

sisve
  • 18,658
  • 3
  • 49
  • 90
Joan Venge
  • 269,545
  • 201
  • 440
  • 653
  • possible duplicate of [Why isn't my public property serialized by the XmlSerializer?](http://stackoverflow.com/questions/575432/why-isnt-my-public-property-serialized-by-the-xmlserializer) – John Saunders Feb 23 '11 at 00:51
  • Joan, the real answer to your question is: "because it's been that way since .NET 1.0, and will never change." – John Saunders Feb 23 '11 at 06:34
  • I see. I was just wondering if there was a technical reason for it like "readonly variables can't even be set through reflection", etc. But since it was just because of design decisions, I understand it now. – Joan Venge Feb 23 '11 at 17:44

1 Answers1

1

Its not possible because As mentioned in MSDN

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport.

But you can use DataContractSerializer. Here is a link to Marc's Answer on SO

Serializing private member data

Update

You can get over that behavior by leaving Auto Implemented properties and have somthing like this:

 private List<Effect> _Effects;  

 public Effect()  
 {  
     _Effects= new List<Effects>();  
 }  

 public List<Effect> Effect
 {  
    get  
     {  
        return _Effects;         
     }  
 }  
Community
  • 1
  • 1
Shekhar_Pro
  • 17,252
  • 7
  • 47
  • 77
  • Thanks this still doesn't explain why read-only properties are not allowed because my properties are public too. – Joan Venge Feb 23 '11 at 00:49
  • Thanks but would it be able to set the value of _Effects correctly once it's done like that? (using non-auto properties) – Joan Venge Feb 23 '11 at 00:59
  • 1
    @Joan: yes, but this only works for properties which are collections. For all others, they need both read and write. – John Saunders Feb 23 '11 at 01:30