Serialization
Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization
Uses of Serialization
Below are some useful custom attributes that are used during serialization of an object
[Serializable] -> It is used when we mark an object’s serializable [NonSerialized] -> It is used when we do not want to serialize an object’s field. [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.
Below is the example of serialization
[Serializable]
internal class DemoForSerializable
{
internal string Fname = string.Empty;
internal string Lname = string.Empty;
internal Stream SerializeToMS(DemoForSerializable demo)
{
DemoForSerializable objSer = new DemoForSerializable();
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, objSer);
return ms;
}
[OnSerializing]
private void OnSerializing(StreamingContext context) {
Fname = "sheo";
Lname = "Dayal";
}
[OnSerialized]
private void OnSerialized(StreamingContext context)
{
// Do some work after serialized object
}
}
Here is the calling code
class Program
{
string fname = string.Empty;
string Lname = string.Empty;
static void Main(string[] args)
{
DemoForSerializable demo = new DemoForSerializable();
Stream ms = demo.SerializeToMS(demo);
ms.Position = 0;
DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;
Console.WriteLine(demo1.Fname);
Console.WriteLine(demo1.Lname);
Console.ReadLine();
}
}