0

I am trying to serialize and deserialize a List of Interface like List; There are some generic classes that inherit this interface like below:

public class BasicQuery<T> : IQuery
{
    public T Value{get;set;}
}

I have created several instances of BasicQuery for different datatypes and added to the list

List<IQuery> ListOfQueries = new List<IQuery>();
BasicQuery<int> q1 = new BasicQuery<int>(); q1.Value = 100;
ListOfQueries.Add(q1);
BasicQuery<string> q2 = new BasicQuery<string>(); q2.Value="Test";
ListOfQueries.Add(q2);

My question is how to serialize and deserialize the List of interfaces to xml which is ineherited by generic child classes. I searched around and found one very useful link https://www.codeproject.com/Articles/38930/XML-Serialization-of-a-Class-Inherited-from-Generi?msg=3159064#xx3159064xx . But that still do not solve my problem. Please suggest.

  • You can't serialize a member whose declared type is an interface, or a collection of values whose declared type is an interface. For confirmation and alternatives, see [XML serialization of interface property](https://stackoverflow.com/q/1333864/3744182). You can, however, serialize a class hierarchy when the type being serialized is abstract, as long as it is not an interface. For how, see [Using XmlSerializer to serialize derived classes](https://stackoverflow.com/q/1643139/3744182). – dbc Nov 22 '18 at 17:57
  • In that case, also can you serialize and deserialize generic class types, as in my code. – sudeep kushwaha Nov 23 '18 at 13:31
  • Yes you can serialize generics, but if the generic parameter is an interface it will not work if there are any serializable members or values of the same type, e.g. if `T` is an interface `ISomeInterface` then `BasicQuery` will not be serializable by `XmlSerializer`, because `public public ISomeInterface Value` will not be serializable. But to give a full answer to your question I would need to see a [mcve]. As it is your question is missing the definition for `IQuery` and so doesn't compile or reproduce your problem. – dbc Nov 26 '18 at 20:59
  • IQuery could be any random interface, lets say `public Interface IQuery { string Name{get;set;} string Description{get;set} }` – sudeep kushwaha Nov 28 '18 at 10:38

0 Answers0