I have a class that has a property that is defined as interface.
Users of my class can assign to this property any class implementation that implements the interface.
I want to be able to load this class state from a textual file on disk. Users should be able to manually modify the xml file, in order to control the application’s operation.
If I try to serialize my class, it tells me I cannot serialize an interface.
I understand that the serializer has no knowledge about the structure of the property’s class, knowing only that it implements an interface.
I would have expected it to call GetType on the member, and reflect into the structure of the actual class. Is there a way to achieve this?
Is there another way to implement my requirement?
Edit: Clarifying my intentions:
Lets say I have this class:
class Car
{
IEngine engine
}
class ElectricEngine : IEngine
{
int batteryPrecentageLeft;
}
class InternalCombustionEngine : IEngine
{
int gasLitersLeft;
}
and the class user has a class with
Car myCar = new Car();
myCar.Engine = new ElectricEngine() {batteryPrecentageLeft= 70};
When I serialize the class myCar, I expect the the xml to resemble this:
<Car>
<Engine>
<ElectricEngine>
<batteryPrecentageLeft>70</batteryPrecentageLeft>
</ElectricEngine>
<Engine>
</Car>
Based on @Jens solution I have created a serializer that does what I need. Thanks Jen.
Here is the code: