0

I'm trying to serialize a class that exposes a property as an interface. When I try to serialize the instance of the class the XmlSerializer throws an InvalidOperationException with the following message:

{"Cannot serialize member SerializationTest.ParkingLot.MyCar of type SerializationTest.ICar because it is an interface."}

I know there are severl ways to solve the problem. But I want to know why an interface cannot be serialized. There is a saying that "You can not serialize an interface. The problem is that an interface is an opaque type. There is no way for the serializer to know what to write out and more importantly what to create when it needs to serialize things back".

Could anyone explain more about this? Could you give me an example? Thank you in advance.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Robin Sun
  • 1,352
  • 3
  • 20
  • 45
  • 7
    You can't instantiate an interface - how would it be deserialized? – Blorgbeard Sep 04 '13 at 05:27
  • 2
    An interface holds no data, only classes that implement the interface can be serialized. – Andy Sep 04 '13 at 05:29
  • Interface by definition is just a definition which should be implemented elsewhere, just add the [NonSerialized] attribute for the field and try to serialize. You could try serializing the other class which implements this interface and then when you deserialize the main class, assign the value for the property manually. – Vignesh.N Sep 04 '13 at 05:54
  • Please find below links http://stackoverflow.com/questions/2639362/why-are-interfaces-not-serializable http://stackoverflow.com/questions/1333864/xml-serialization-of-interface-property – Vimal CK Sep 04 '13 at 06:08

0 Answers0