sameh.q
sameh.q

Reputation: 1709

Serializing an instance of an Interface that have a definition of a list of another interface

This might sound like a repeated question from other topics, but it defers in the Interface definition.

I have an Interface, lets say named IClass1, which contains in its definition a list of interfaces, say IClass2

I have a business unit to implement this interface; implementation naturally will be like this

class Class1: IClass1
{
    ....whatever properties
    List<IClass2> DataItems { get; set; }
}

class Class2:IClass2
{
    ...whatever properties
}

The problem is that, XmlSerializer will complain about the list in Class1, because it is an interface! So my question is: Simply, I always know what is the type of the instances that should be de-serialized in DataItems list, which will be of type Class2, how to tell my XML serializer that?

I've saw a lot of workarounds, using a dummy properties and ignore the list of interfaces during the serializing/de-serializing process is the most suitable one I think, and I i certainly don't want to invent my own serializer or re implement serialization in my classes

Upvotes: 0

Views: 63

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109567

If you are using DataContracts, you can use KnownTypeAttribute to give the deserializer a list of one or more types that it should use when deserializing.

The version that takes a string parameter lets you specify the name of a method that will return a sequence of types, which can be easier to use in some circumstances.

The link I gave has some sample code at the end of the page.

Upvotes: 1

Related Questions