views:

364

answers:

3

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?

+1  A: 

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?

Chad Grant
Deviant is correct.. Interface is the contract... your object, implementing that interface.. is agreeing to that contract. You serialize your object, not the contract.
datacop
A: 

I think you will have to handle serialization explicitly by implementing ISerializable. Think about how deserialization can determine what concrete class to use for IState. It does not know. That's why you would need to handle serialization on your own.

Mehmet Aras
A: 

Consider having your IState interface inherit from ISerializable:

public interface IState : ISerializable

Read up on ISerializable first. It adds a few complications to the matter.