Often, the software you create must have the ability to persist data for later retrieval. When the data you save is only for your application or you are looking for an efficient way of storing your objects, BinaryFormatter is the answer. BinaryFormatter class is in the System.Runtime.Serialization.Formatters.Binary namespace. The BinaryFormatter class allows you to quickly convert objects into binary form for saving to a file or sending across network. The primary requirement for enabling serialization is marking the type as Serializable. In C#
[Serializable()] class Person
{
public string Name;
}
Serializing
Now the Person class is ready for serialization. Let us see how to do just that.
private void Save(Stream stream,Person p)
{
BinaryFormatter formatter=new BinaryFormatter();
formatter.Serialize(stream,p);
}
Here the Save() method receives the Stream for writing the data and the Person object which is to be saved. Then it creates the BinaryFormatter and call its Serialize() method passing the required parameters. I think those parameters are self explanatory.
Deserializing
Deserializing is also very simple. Take a look at the below code.
private Person Load(Stream stream)
{
BinaryFormatter formatter=new BinaryFormatter();
return (Person)formatter.Deserialize(stream);
}
So, serializing and deserializing objects in .NET is as simple as it can get. Mark Types which you would like to be serializable with Serializable attribute and you are ready to go. Although it looks as nothing can go wrong, there are things to be remember. For example, effectively handling situation where you add extra fields to your types and errors happens when data serialized with old type is deserialized into new types. Once you lookout for such things and use serialization properly, it can be a great time saver.
Hope it helps anyone,