In my WP8 app I have a special type of ‘settings’ objects that are stored in IsolatedStorageSettings.ApplicationSettings. These objects set some initial state in their constructors and that state may be changed later.
Now the problem is that apparently when object is deserialized it’s constructor gets called again, thus resetting changes in state and it is not what I want.
Basically something like this:
class Test
{
public int a { get; set; }
public Test() { a = 1; }
}
Test x = new Test();
x.a = 2;
IsolatedStorageSettings.ApplicationSettings["test"] = x;
IsolatedStorageSettings.ApplicationSettings.Save();
// on next app launch
Test x = IsolatedStorageSettings.ApplicationSettings["test"] as Test;
Debug.writeLine(x.a) // 1, I want 2
Can I change the process somehow so that object’s constructor will not be called on deserialization?
Of course a deserializer has to call the type’s constructor, because it needs to first create an instance of a type (the object) and then fill the object’s properties with the data found in the serialized input.
So, a quick workaround is to leave the default parameterless constructor blank, and do your special init’s in a constructor with a parameter or with a dedicated call to a method to initialize your object.
OR, use a dedicated type for serializing/deserializing, a DTO (Data Transfer Object) and then use from that object whatever information you need.
But anyway, something is fishy, in your code sample, it should work as you expect because first the deserializer would call the constructor and only after that set the properties, you can test this by setting breakpoints in the class constructor and in the setters of individual properties to see the process workflow.