Serialization

Idea: Test of Serialization and persistensy of objects in a binary file.
Background: Basic Serialization

A) Implement class Car and class Owner from the following the Class-diagram:

 

Notice: Class Car and Class Owner must be annotated with Serializable ( [Serializable] ), List are Serializable by default.

Make a test of Serialization in C#:

B) Create an object of class Owner and save the objekt in a binary file, like this:

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("Owner.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream,owner);
stream.Close();

What is the difference between FileMode.Create, FileMode.CreateNew and FileMode.Append ?

C) Read in the object from the binary file using Deserialization, like this:

Stream stream = new FileStream("Owner.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
Owner owner = (Owner)formatter.Deserialize(stream);
stream.Close();

Notice: it's nessesary to use a type-cast (the return-type of the Deserialize() method is Object)


D) Create some Owner and Car objects (remember to associate owners to cars). Create a List owners of Owners and a List cars of Cars and add the objects to the lists.
Create a List persistence of Objects and add the lists owners and cars to the List (see the class diagram above).

Finally test serialization of persistence.

Can you get all your object again? Is there only one version of each Owner object? or have the Deserialize-method created more than one clone? (e.g. what happens if a owner owns more than one car?)

Notice: The default Equals method (defined in and inherit from class System.Object) test for physical eqvivalence - it simply compare references.