Exception excluded interface "not marked with serializable attribute"

I have a very strange exception in my C # application: when trying to deserialize a class that contains a generic List<IListMember>

(where list entries are specified by the interface), an exception is thrown saying "the type ... IListMember is not marked with a serializable attribute" (phrasing may be slightly different, my VisualStudio is not in English).

Now interfaces cannot be Serializable; the class actually in the list that implements IListMember [Serializable]

; and yes i checked what IListMember

is actually defined as an interface and not randomly as a class!

I tried to reproduce the exception in a separate test project containing only the class containing the list and its members, but there it serializes and deserializes happily: /

Does anyone have any good ideas on what this might be?

Edit:

We use BinarySerializer

; and I repeat that when checked out into a test project, the class is serialized happily. So I don't need a workaround to serialize the containing class List<IThing>

as it usually works fine (as long as the actual classes that implement IThing

are serializable); what i am looking for is the reason it may not work at this particular time ...

I have now applied a workaround (taking each member of the list in turn, along with the number of entries and List

manually recreating ), but would really like to know what that might be for future references.

+2


a source to share


2 answers


It doesn't matter that the class supporting the interface is serializable. Interfaces cannot be serialized, period.

For deserialization, the serializer must be able to create a concrete type, and it defines that type by reflecting the fields / properties of the class to be deserialized.

If the type of one of these properties is an interface, then it can never build a concrete type to assign to that member. All he sees is an interface, he doesn't know which class originally implemented it when the data was serialized.



If you want a class to be serializable, each class in the object graph must be specific. Allowed interfaces.

(Postscript: Actually, I kind of lied, BinaryFormatter

can serialize / deserialize directly to / from interface types, but I strongly suspect that's not what is being used here.)

+2


a source


Easy way (albeit ugly) Wrap your list:

public ListMemberCollection : List<IListMember>, ISerializable
{
    // Implement ISerializable Here
}

      

An alternative (albeit better) way to AbstractBaseClass:



[Serializable]
public ListMemberBase : IListMember
{
   // Implement abstract versions of everything
}

      

Opportunity ?: (in your other class)

class TheClassYoureSerializing
{
   [Serializable]
   public List<IListMember> list { get; set; }
}

      

-1


a source







All Articles