Lets say i have a class
[Serializable()]
public class Car
{
public string model;
public int year;
}
I serialize that to disk named "car.xx". Then i add a property to my Car class so it will be like this:
[Serializable()]
public class Car
{
public string model;
public int year;
public string colour;
}
Then i deserialize "car.xx" ( that contains 2 fields ) to my current car class that contains 3 fields, which will make the "colour" property of our Car class null.
How do i set that "new properties" dont get null values? Setting them in the constructor wont help.
I am using BinaryFormatter serializer
I want string values that are null to be replaced with ""
if you are not using XmlSerializer then consider using OnDeserializedAttribute, OnSerializingAttribute, OnSerializedAttribute, and OnDeserializingAttribute attributes
see this.
like:
[Serializable()]
public class Car
{
public string colour;
public string model;
public int year;
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
if (colour == null)
{
colour = string.Empty;
}
}
}
It all depends on the serializer.
Some serializer skip constructors; some serializers run the default constructor. Some let you choose. Some offer serialization callbacks.
So depending on the serializer:
or worst-case, implement custom serialization (ISerializable
/ IXmlSerializable
/ etc, depending on the serializer)
For example, with BinaryFormatter
:
[Serializable]
public class Car : IDeserializationCallback
{
public string model;
public int year;
public string colour;
void IDeserializationCallback.OnDeserialization(object sender)
{
if (colour == null) colour = "";
}
}
With other serializers, it might use [OnDeserialized]
instead. Note; personally I wouldn't be exposing public fields, even in a DTO. But if you are using BinaryFormatter
, changing this is now a breaking change. For completeness, I also wouldn't be using BinaryFormatter
- it is not very friendly to this. Other serializers are available that will hurt you less.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With