3
\$\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;
 }
}
asked Dec 23, 2011 at 22:50
\$\endgroup\$

1 Answer 1

2
\$\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());
 }
 }
}
answered Dec 24, 2011 at 2:12
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.