0

I need to serialize to xml a list containing objects of type Pair<T,U>.

First, I've created a class PairList to hold the list of the pairs and then I've created the actual class which represents a pair of two values, key and value.

[XmlRoot("pairList")]
public class PairList<T,U> 
{
    [XmlElement("list")]
    public List<Pair<T,U>> list;

    public PairList()
    {
        list = new List<Pair<T, U>>();
    }
}

public class Pair<T, U>
{
    [XmlAttribute("key")]
    public T key;

    [XmlAttribute("value")]
    public U value;

    public Pair(T t, U u)
    {
        key = t;
        value = u;
    }
}

Then, I tried serializing it:

PairList<string,int> myList = new PairList<string,int>();
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
try
{
    XmlSerializer serializer = new XmlSerializer(typeof(PairList<string, int>));
    TextWriter tw = new StreamWriter("list.xml");
    serializer.Serialize(tw, myList);
    tw.Close();
}
catch (Exception xe)
{
    MessageBox.Show(xe.Message);
}

Unfortunately I am getting an exception: There was an error reflecting type: PairList[System.String,System.Int32]. Any ideas on how I could avoid this exception and serialize the list are welcome.

svick
  • 236,525
  • 50
  • 385
  • 514
Teo
  • 3,394
  • 11
  • 43
  • 73

1 Answers1

1

Just add a parameterless constructor to your Pair<T, U> class and it will work...

public Pair()
{
}
I4V
  • 34,891
  • 6
  • 67
  • 79
  • Thanks :). Could you tell me why that constructor was causing the problem? – Teo Jun 09 '13 at 16:06
  • 1
    @Theo. http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/0c9102a7-5e38-4f65-af25-cdbf6362bd5e/ http://stackoverflow.com/questions/267724/why-xml-serializable-class-need-a-parameterless-constructor – I4V Jun 09 '13 at 16:13