Saving and Loading Readonly Properties
Each readonly property requires a constructor parameter with the same name in order to be saved and loaded.
For example, in the below script, we have a class called ReadonlyClass
, it has a readonly property called myReadonlyProperty
:
public class ReadonlyClass {
private readonly string myReadonlyProperty;
}
But after a save and load attempt, you'll notice that the myReadonlyProperty
is saved but it is not loaded, that's because we don't have any constructors that accepts the readonly property as an parameter in order to assign it, so to make it work, we have to add a constructor to our class:
public class ReadonlyClass {
private readonly string myReadonlyProperty;
public ReadonlyClass(string myReadonlyProperty) {
this.myReadonlyProperty = myReadonlyProperty;
}
}
Now the readonly property will be saved and loaded properly.
Note
The name of the constructor parameter should be the same as the name of the readonly property for matching the parameter position and its name in serialization process.