Page 155 - CSharp/C#
P. 155
Assume we want to add a "Rating" to our Vector and we want to make sure the value always
starts at 1. The way it is written below, it will be 0 after being deserialized:
[Serializable]
public class Vector
{
public int X;
public int Y;
public int Z;
[NonSerialized]
public decimal Rating = 1M;
public Vector()
{
Rating = 1M;
}
public Vector(decimal initialRating)
{
Rating = initialRating;
}
}
To fix this problem, we can simply add the following method inside of the class to set it to 1:
[OnDeserializing]
void OnDeserializing(StreamingContext context)
{
Rating = 1M;
}
Or, if we want to set it to a calculated value, we can wait for it to be finished deserializing and then
set it:
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
Rating = 1 + ((X+Y+Z)/3);
}
Similarly, we can control how things are written out by using [OnSerializing] and [OnSerialized].
Adding more control by implementing ISerializable
That would get more control over serialization, how to save and load types
Implement ISerializable interface and create an empty constructor to compile
[Serializable]
public class Item : ISerializable
{
private string _name;
https://riptutorial.com/ 101

