Self-deserialising object

  • Thread starter Thread starter Paul E Collins
  • Start date Start date
P

Paul E Collins

I'm using XmlSerializer to write objects of my own class to disk. I'd prefer
to do this from inside the class, so that I can just write
Settings.Load(...) and Settings.Save(...).

The code I tried is below. However, the Load method fails because the 'this'
object is read-only.

Is there a simple way for an object to deserialise itself, or am I better
off doing it from outside the class?

public void Save(string strFilename)
{
XmlSerializer x = new XmlSerializer(typeof(MyObject));
using (TextWriter writer = new StreamWriter(strFilename))
{
x.Serialize(writer, settings);
writer.Close();
}
}

public void Load(string strFilename)
{
XmlSerializer x = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StreamReader(strFilename))
{
this = (MyObject) x.Deserialize(reader);
reader.Close();
}
}

P.
 
(Apologies if this comes out twice - if it does, ignore the other
post.)

Paul E Collins said:
I'm using XmlSerializer to write objects of my own class to disk. I'd prefer
to do this from inside the class, so that I can just write
Settings.Load(...) and Settings.Save(...).

The code I tried is below. However, the Load method fails because the 'this'
object is read-only.

Is there a simple way for an object to deserialise itself, or am I better
off doing it from outside the class?

It makes more sense to have Load as a static method which returns a new
instance of the class.
 
Back
Top