Skip to content

Serialization

Mario Gutierrez edited this page Jan 8, 2017 · 24 revisions

Serialization is the process of persisting the state of an object to a file or memory buffer. The persisted data contains all the necessary information you need to reconstruct (deserialize) the state of the object.

Serializable marks a class serializable.

[Serializable]
public class UserPrefs
{
  public string WindowColor;
  public int FontSize;
}

Example using BinaryFormatter to write a Serializable object to a file stream.

UserPrefs userData = new UserPrefs { WindowColor = "Blue", FontSize = 24 };
BinaryFormatter bf = new BinaryFormatter();
using (Stream fs = new File.OpenWrite("user.dat"))
{
  bf.Serialize(fs, userData); 
}

Clone this wiki locally