2
\$\begingroup\$

I have a C# WinForms app containing a ListBox control, which I populate with objects of type BukkitServer. When an object is added or removed from the list, I want to write them to an XML file. I have a static method in a helper class that takes an ICollection argument and achieves this.

However, since the ListBox.ObjectCollection class is not serializable (fittingly, since it contains elements of type object), I wrote a helper method to convert it to a List<BukkitServer>.

It feels like a hack, though, and I feel (hope) there is a cleaner answer.

Any other comments and criticisms are welcome as well.

static class BukkitServerDataWriter {

    public static void SaveServers(ICollection objects) {

        using (XmlTextWriter writer = new XmlTextWriter("servers.xml", Encoding.UTF8)) {
            XmlSerializer xml = new XmlSerializer(
                typeof(List<BukkitServer>), 
                new Type[] { typeof(BukkitServer) });

            List<BukkitServer> servers = MakeBukkitServerList(objects);
            xml.Serialize(writer, servers);
        }

    }


    private static List<BukkitServer> MakeBukkitServerList(ICollection collection) {

        List<BukkitServer> servers = new List<BukkitServer>();
        foreach (object obj in collection) {
            servers.Add((BukkitServer)obj);
        }

        return servers;
    }

}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If you don't mind using a little bit of LINQ, it can be simplified (and optimized) as such:

static class BukkitServerDataWriter
{
    private static readonly XmlSerializer xml = new XmlSerializer(
        typeof(List<BukkitServer>),
        new[] { typeof(BukkitServer) });

    public static void SaveServers(ICollection objects)
    {
        using (var writer = new XmlTextWriter("servers.xml", Encoding.UTF8))
        {
            xml.Serialize(writer, objects.Cast<BukkitServer>().ToList());
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ My pleasure. Glad to assist. \$\endgroup\$ Commented Dec 24, 2011 at 3:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.