Click here to Skip to main content
Click here to Skip to main content

Store Generic Classes in Settings

By , 24 Aug 2012
 

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 //Custom class for list
{
    public int MyProperty { get; set; } //just for example
}

public class MyClassList : List<MyClass> { } //Wrapper class of list of type MyClass 
//Simple Console Application for Test
static void Main(string[] args)
{
    MyClassList list = new MyClassList();
    list.Add(new MyClass() { MyProperty = 5 });
    Properties.Settings.Default.MySetting = list; //MySetting is type of MyClassList
    Properties.Settings.Save();
}    

After compiling this test application, you can delete your code and see if settings have saved:

//Simple Console Application for test
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

m_Plb
Software Developer (Junior)
Georgia Georgia
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberChristian Amado24 Aug '12 - 16:42 
GeneralRe: My vote of 5memberm_Plb25 Aug '12 - 2:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 24 Aug 2012
Article Copyright 2012 by m_Plb
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid