Page 160 - CSharp/C#
P. 160
{
var item = new Item
{
Name = "Orange"
};
var bytes = SerializeData(item);
var deserializedData = (Item)DeserializeData(bytes);
}
private static byte[] SerializeData(object obj)
{
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
private static object DeserializeData(byte[] bytes)
{
var binaryFormatter = new BinaryFormatter
{
Binder = new MyBinder()
};
using (var memoryStream = new MemoryStream(bytes))
return binaryFormatter.Deserialize(memoryStream);
}
}
}
Some gotchas in backward compatibility
This small example shows how you can lose backward compatibility in your programs if you do not
take care in advance about this. And ways to get more control of serialization process
At first, we will write an example of the first version of the program:
Version 1
[Serializable]
class Data
{
[OptionalField]
private int _version;
public int Version
{
get { return _version; }
set { _version = value; }
}
}
And now, let us assume that in the second version of the program added a new class. And we
need to store it in an array.
https://riptutorial.com/ 106

