Tom Wright
Tom Wright

Reputation: 11489

Is it possible to deserialize to the current class?

I have a settings class that I want to be able to serialize and deserialize to save and load settings to a file.

With hindsight, I'd have designed my whole app to create an instance of settings when needed. As it is, my settings are persistent (mimicking the default application settings behaviour). Given my current architecture, I can do the following:

public void Save()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Create);
    XmlSerializer x = new XmlSerializer(this.GetType());
    x.Serialize(stream, this);
}

Obviously, I can't do this:

public void Load()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Open);
    XmlSerializer x = new XmlSerializer(this.GetType());
    this = x.Deserialize(stream);
}

But is there a way to update all the public properties of the current class to match those of the deserialized object?

(I suppose the more general questions is: "Is there an efficient way to update one class based on the contents of another?")

Upvotes: 1

Views: 1895

Answers (3)

Tim S.
Tim S.

Reputation: 56556

Another option is AutoMapper.

Upvotes: 0

LiFo
LiFo

Reputation: 128

I would make the settings class an singelton and have a static Instance to it then you could call load and save on that instance

public class MySettings
{
    private static MySettings _instance;
    public static MySettings Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MySettings();
                // maby call Load();
            }
            return _instance;
        }
    }
    private MySettings()
    {  
        //set default values
    }

    public void Load()
    {
        Stream stream = File.Open("settings_test.xml", FileMode.Open);
        XmlSerializer x = new XmlSerializer(this.GetType());
        _instance = (MySettings)x.Deserialize(stream);
    }

    public void Save()
    { 
        Stream stream = File.Open("settings_test.xml", FileMode.Create);
        XmlSerializer x = new XmlSerializer(this.GetType());
        x.Serialize(stream, _instance);
    }
}

Upvotes: 3

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31743

I would use a static method

MyClass myclass = MyClass.Load("settings.xml")

Otherwise you can achive that with reflection.

Found this example via google: http://www.csharp-examples.net/reflection-examples/

Upvotes: 2

Related Questions