views:

1193

answers:

1

Is it possible to save an ArrayList of custom objects to the application user settings without resorting to custom serialization?

For example, given a basic data class containing only public get/set properties and private backing fields:

[Serializable]
class SimpleClass()
{
  ...   
}

When I run the following in code, and then restart the application, the ArrayList setting named MyList is always null, ie it was not saved.

if (Properties.Settings.Default.MyList==null)
{
    Properties.Settings.Default.MyList=new ArrayList();
}

Properties.Settings.Default.MyList.Add(new SimpleClass(DateTime.Now.ToString()));

Properties.Settings.Default.Save();

I realise that an ArrayList is not typed, ie. it holds a collection of objects. However it is simple to use GetType() on each object to determine the actual type. This should allow serialization to occur, shouldn't it?

I also know how to get around this performing some custom serialization. It's just a pain this doesn't appear to work as it would be by far the most convenient for simpler situations.

Any ideas?

A: 

If you are using XML Serialization, you can use the XmlArrayItem attribute.

 [XmlArray("Items")]
 [XmlArrayItem("A.Thing",typeof(Thing))]
 [XmlArrayItem("A.Different.Thing",typeof(Whatzit))]
 public System.Collections.ArrayList List;

This requires that you know the different types that may be present in the ArrayList at compile time.

Cheeso