C#: To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object)

LKB picture LKB · May 31, 2013 · Viewed 15.7k times · Source

I have the following code:

private static string FindAppointmentsAsXmlString(CalendarView calendar, ExchangeService serv)
{
    FindItemsResults<Appointment> appointments = serv.FindAppointments(WellKnownFolderName.Calendar, calendar);

    var serializer = new XmlSerializer(appointments.GetType());
    var writer = new StringWriter();

    try
    {
        serializer.Serialize(writer, appointments);
        Console.WriteLine(writer.GetStringBuilder().ToString());
        Console.ReadLine();
    }
    catch (Exception ex) 
    {
        Console.WriteLine(ex);
        Console.ReadLine();
    }

    return writer.GetStringBuilder().ToString();
}

When initializing serializer, I get the exception:

To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy.

Microsoft.Exchange.WebServices.Data.FindItemsResults does not implement Add(System.Object).

I've searched around, and I've come to the conclusion that I have to add a public Add(Object obj) method. Now I'm not really sure what this method should contain or when it is called, can anyone point me in the right direction? Does the Add method need to manually add each appointment?

Some links I found helpful: here here

Much appreciated.

Answer

Jesse Sweetland picture Jesse Sweetland · May 31, 2013

The Add() method should have a single argument of the type of the elements in the IEnumerable object. For example, if FindItemsResults implements IEnumerable<T> then you can add method void Add(T value). If you want FindItemsResults to be read-only, you could convert FindItemsResults to a List via the ToList() extension method and serialize the list rather than the FindItemsResults object itself.