0

I'm trying to serialize into a Xml File an object which is declared as ILIst, but it's an instance of List. The exception tells me the reason: You can't serialize an interface.

This is really necessary in my design, or what other way do I have to serialize it?

Nick DeVore
  • 9,748
  • 3
  • 39
  • 41
Darf Zon
  • 6,268
  • 20
  • 90
  • 149
  • 1
    There are many duplicates around, try out using SEARCH – sll Apr 03 '12 at 15:14
  • possible duplicate of [How to serialize an IList?](http://stackoverflow.com/questions/464525/how-to-serialize-an-ilistt) – jrummell Apr 03 '12 at 15:19
  • possible duplicate of [Why are interfaces not \[Serializable\]?](http://stackoverflow.com/questions/2639362/why-are-interfaces-not-serializable) – nawfal Jul 10 '14 at 15:35

5 Answers5

2

You have to know what concrete type to instantiate.

The serializer has to go by the metadata, not runtime type. If all you knew was that your target object had to implement IList, what would you construct? There not necessarily even a class that implements it.

harpo
  • 41,820
  • 13
  • 96
  • 131
1

This should not be a problem, you can always use object.GetType(). Here's an example:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

class Program {
    static void Main(string[] args) {
        System.Collections.IList list = new List<int> { 1, 2, 3 };
        var ser = new XmlSerializer(list.GetType());
        ser.Serialize(Console.Out, list);
        Console.ReadLine();
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    well, I've got an object (which I plan to serialize) that it has a property where it's a list, do you think I can Specify the type in XmlArray? – Darf Zon Apr 03 '12 at 15:28
1

I suppose the reason you need to keep the design with IList is because it's a common interface to other module. One possible solution:

Instead of:

    [XmlElement("Test")]
    public IList<String> Tests
    {
        get;
        set;
    }

You can probably try:

    [XmlElement("Test")]
    public List<String> TestList
    {
        get;
        set;
    }

    [XmlIgnore]
    public IList<String> Tests
    {
        get { return TestList; }
    }

This way you can keep the same interface, and meanwhile take advantage of serialize/deserialize functionality in .Net Xml library.

Jiaji Wu
  • 459
  • 3
  • 10
0

I can see two options:

  1. You can cast it back to List before when passing it to the serializer. Not ideal, but it would work.
  2. You iterate over the IList and serialize each item to the same stream independently.
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

You can't serialize an interface because it doesn't contains any data. May be the best you can do is to implement ISerializable to control the serialization yourself.

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44