Introduction
There are some situations where it's very useful to store an array of custom objects in settings. I had one today. I've tried using
ArrayList but my custom objects were not saved. I thought it would be great if I could directly save list of custom type in settings. This meant that my only problem was how to make use of generics in settings that was solved quite simply with this method.
Limitation
This can't be used for
Dictionary and
Tuple.
Using the Code
To use generic classes in settings, you have to create a wrapper class that extends generic class and use it as type of setting property. Here's a simple example:
public class MyClass
{
public int MyProperty { get; set; }
}
public class MyClassList : List<MyClass> { }
static void Main(string[] args)
{
MyClassList list = new MyClassList();
list.Add(new MyClass() { MyProperty = 5 });
Properties.Settings.Default.MySetting = list;
Properties.Settings.Save();
}
After compiling this test application, you can delete your code and see if settings have saved:
static void Main(string[] args)
{
foreach (MyClass item in Properties.Settings.MySetting)
{
Console.WriteLine(item.MyProperty);
}
Console.Read();
}
Conclusion
I hope this will be useful for someone who'll have the same needs as I had and won't spend one hour on thinking about how to do what he wants.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.