C# – Refactoring class to interface without breaking serialization in C#

cnetrefactoringserialization

I have a class that I have serialized to disk on local users machines. I need to refactor this class and I changed all objects (anything except enums, string, numbers) to interfaces. Underneath it is still the same concrete class. my concern is breaking existing users persistance

From:

public class Foo
{
     public double Count;
     public State MyState;
}

To

public class IFoo
{
     public double Count;
     public IState MyState;
}

but now I am getting errors from the serialization code that says "can't serialize because its an interface"

the error states:

"There was an error reflecting type 'Foo'."
"Cannot serialize member 'Foo.My' of type 'IState', see inner exception for more details."

what is the best way around this?

Best Answer

You cannot serialize interfaces because the amount of types that can implement the interface is infinite and the serializer does not know what concrete type it is.

class A : IFoo {}
class B : IFoo {}
class C : IFoo {}
//snip//

IFoo f = new A();
     f = new B();
     f = new C();

You must specify if you are serializing A,B or C.

Another way to think of it is when deserializing to IFoo, how would you know which to create ... A, B or C .. etc?