Tuesday, June 1, 2010

Serialize Objects

Serialization is an efficient concept for converting and subsequently saving objects.
In many programs the entered data is not thought for unique use, but supposed to be reused the next time when the program is executed.
Accordingly, data has to be saved. With streams data can be written in files or the memory. StreamWriter and StreamReader are probably the most known representatives, they excel in reading and saving text files.

But, saving data as text, is in most cases costly, unsafe and not exactly elegant.
In .Net there are possibilites to convert data in a specific format and to write them in a file - it can be serialized. Basically, there are the classes BinaryFormatter, SoapFormatter and XmlSerializer.
With XmlSerializer data can be serialized in the XML - format, with SoapFormatter in the Soap - format.
BinaryFormatter serializes object into a binary format, for this class I want to post an example:
We construct a minimal employee management as example. Employees are saved as instances of the class Employee:
public class Employee
static int GlobalID = 0;

int ID;
string Surname, Prename;
double Salary;
string Email;

public Employee(string surname, string prename)
ID = GlobalID++;
Surname = surname;
Prename = prename;
The attribute [Serializable] is necessary, so that the class can be serialized.
For the easy example the serialization and deserialization happens on loading the form:
private void Form1_Load(object sender, EventArgs e)
List DemoList = new List();
DemoList.Add(new Employee("Wurst", "Hans"));
DemoList.Add(new Employee("Mustermann", "Max"));


List DeserializedList = DeserializeEmployees();
In this function at first a list of the type Employee is created and "Hans Wurst" and "Max Mustermann" are added.
Then a function to serialize this data is called, which looks as follows:
private void SerializeEmployees(List employees)
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(Application.StartupPath + "\\list.emp", FileMode.Create);
bf.Serialize(fs, employees);
The class BinaryFormatter provides us with the function Serialize(), which expects as parameter a stream as well as the object which is to be serialized.
In this case the list employees is written via FileStream to the file "list.emp" in the application directory.

In Form1_Load(), afterwards the process is reversed and a function for deserialization is called:
private List DeserializeEmployees()
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(Application.StartupPath + "\\list.emp", FileMode.Open);
List Result = (List)bf.Deserialize(fs);
return Result;
BinaryFormatter provides a function Deserialize() as well, which creates an object from the given stream. This is then converted to the requested type (here List) and returned.

In the end, the list DeserializedList in Form1_Load() contains the same employees as the original list.

No comments:

Post a Comment