Storing Custom Classes in User Settings?

P

Paul Hadfield

Hi,

I'm not having a lot of luck googling for this one, I want to be able to
store a custom class in the user settings (DotNet2.0, win app). I don't
wish to create public get / set properities for all the things I want to
persist just for storing in the user settings file (because that would allow
other apps to access / change data they shouldn't be able to).

I understand how to browse to the object in VS2005 to add an entry to the
settings file., but I'm not sure what I need to do to my class to get it to
work. Using a very basic example below, is there an interface I should
inherit from? I'm guessing there must be an interface that defines at least
two methods, one that returns an xml string of the parameters to persist and
another that takes that xml string and allows the class to initalise itself
internally. (Note I really don't want to add Get/Set for val1 and val2 just
to get default persistance of all public properties).

Thanks in Advance,

- Paul

public ClassA
{
private int val1;
private string val2;

ClassA( val1, val2)
{
this.val1 = val1;
this.val2 = val2;
}

public bool Valid()
{
return ((val1 > 10) && !string.IsNullOrEmpty(val2));
}

public string Text()
{
return (val1.ToString() + ' ' + val2);
}
}
 
K

Kevin Spencer

The class must be serializable as XML. In order for it to be serializable as
XML, keep in mind that XML Serialization does not serialize classes without
parameterless constructors, so you need to add one to your class. In
addition, private fields, methods, and read-only (get only) properties are
not serialized. See http://msdn2.microsoft.com/en-us/library/182eeyhh.aspx
for more information.

--
HTH,

Kevin Spencer
Microsoft MVP
Software Composer
http://unclechutney.blogspot.com

In case of Minimalism, break Philip Glass.
 
P

Paul Hadfield

Thanks for your answer - when I couldn't find anything online I had wondered
if this was using the Xml Serialisation object as I've seen it before
posting objects on a message queue. I had hoped that you would be able to
either override the Xml Serialisation object for saving particular classes -
or have the object inherit from a common interface and provide specialised
functionality that the Xml Serialisation provides.

As I don't want to provide a default constructor and expose the private
attributes / change the read only properties; I guess the best solution
would be to create a thin helper class, that just contains the data I wish
to be saved (and no functionality) and then pass this into / from my class
before serialisation. That way I can keep the encapsulation in my class /
application and also use the functionality provided by Xml Serialisation.

- Paul.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top