Why I could not serialize a tuple in C#? [duplicate]
For XmlSerializer
to be able to do its job it needs a default contructor. That is a constructor that takes no arguments. All the Tuple<...>
classes have a single constructor and that constructor takes a number of arguments. One for each value in the tuple. So in your case the sole constructor is
Tuple(T1 value1, T2 value2)
The serializer is looking for a constructor with no arguments and because it can't find it, you get the exception.
you could create a mutable class, that could be substituted for tuples for the purpose of serialization
class MyTuple<T1, T2>
{
MyTuple() { }
public T1 Item1 { get; set; }
public T2 Item2 { get; set; }
public static implicit operator MyTuple<T1, T2>(Tuple<T1, T2> t)
{
return new MyTuple<T1, T2>(){
Item1 = t.Item1,
Item2 = t.Item2
};
}
public static implicit operator Tuple<T1, T2>(MyTuple<T1, T2> t)
{
return Tuple.Create(t.Item1, t.Item2);
}
}
You could then use it the following way
XmlSerializer formatter = new XmlSerializer(
typeof(List<List<MyTuple<String, CodeExtractor.StatementNode>>>));
formatter.Serialize(fs, results.SelectMany(
lst => lst.Select(
t => (MyTuple)t
).ToList()
).ToList());
As the exception tells you: The Tuple<T1, T2>
has NO parameterless constructor which is needed by the serializer.