Why can't I serialize an object with a struct in it?

I have an "options" object that I'm trying to save to Settings

public class MainWindow
{
    public MyOptions MyOptions => (MyOptions)DataContext;

    public MainWindow()
    {
        InitializeComponent();

        DataContext = Settings.Default.MyOptions ?? new MyOptions();
    }

    private void OnOptionsChanged(object sender, PropertyChangedEventArgs e)
    {
        Settings.Default.MyOptions = MyOptions;
        Settings.Default.Save();
    }

    // etc.
}

MyOptions contains (among other things) a struct-value

public class MyOptions
{
    private MyStruct _myStruct;

    public MyOptions()
    {
        _myStruct = someDefaultValue;
    }

    // etc.
}

MyStruct contains only a single int:

public struct MyStruct
{
    private readonly int _someValue;
    public MyStruct(int someValue)
    {
        _someValue = someValue;
    }

    // etc.
}

When I make the call to Settings.Default.MyOptions = MyOptions;, all the values are set correctly, including myStruct.

However, when I restart the program and load the options with DataContext = Settings.Default.MyOptions, all the values are correctly loaded except for _myStruct, which defaults to 0!

According to everything I've read, this code should work. I've tried adding the [Serializable] attribute to both the class/struct, as well as implementing ISerializable (which I shouldn't have to do), but neither helped. What am I missing?

Upvotes: 1

Views: 413

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

Settings are serialized as XML, which has a limitation of excluding readonly members.

Removing readonly qualifier should fix this problem:

public struct MyStruct {
    internal int _someValue;
    public MyStruct(int someValue) {
        _someValue = someValue;
    }
}

Upvotes: 2

gabba
gabba

Reputation: 2880

Try this struct, in my test case it serialized right way:

public struct MyStruct
{
    public int SomeValue { get; set; }
}

Upvotes: 1

Related Questions