views:

64

answers:

4

Hello, how can i serialize this class?

public class MyClass    {
    IInterface MyProperty { get; set;}
}
A: 

Make the class that implements IInterface Serializable like you normally would and it will all work.

Jouke van der Maas
The Serializable attribute has nothing to do with XML serialization...
Thomas Levesque
+1  A: 

You need to add a setter to MyProperty as Xml serialization rules mandate that serialization must be able to round-trip i.e. it must be able to get the property for serialization, then set the property for deserialization.

chibacity
sorry about misunderstanding, i need a way to serialize property which is interface, instantiated of course
aron
Sorry was being a bit literal there. If it's an interface you'll need to follow Thomas's answer, but you will still need to have a setter on your property.
chibacity
+1  A: 

As chibacity said, you need to add a setter to the property. You also need to add the XmlInclude attribute to the property to specify the possible implementing types, otherwise the XmlSerializer won't know what type to instantiate when deserializing

Thomas Levesque
A: 

The XmlSerializer cannot serialize interfaces.

If you know the concrete types you will be dealing with in advance then you can use the XmlInclude approach. If not then there have been a few discussions about how to handle this:

Tuzo