Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.

Similar presentations


Presentation on theme: "Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields."— Presentation transcript:

1 Lecture 19 Serialization Richard Gesick

2 Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields. C# provides such a mechanism, called object serialization. A serialized object is an object represented as a sequence of bytes that includes the object’s data, its type and the types of data stored in the object. After a serialized object has been written to a file, it can be read from the file and deserialized. 14-2

3 Serialization If you are writing binary information into a file, you probably won't be able to read it via a text editor Works on objects, but the class must be marked as serializable (and is recursive) 14-3

4 Serialization Class BinaryFormatter enables entire objects to be written to or read from a stream. BinaryFormatter method Serialize writes an object’s representation to a file. BinaryFormatter method Deserialize reads this representation from a file and reconstructs the original object. Both methods throw a SerializationException if an error occurs during serialization or deserialization. 14-4

5 Creating a File Using Object Serialization The classes for objects that we wish to serialize must include this attribute in their declarations or must implement interface ISerializable. In a serializable class, you must ensure that every instance variable of the class is also serializable. 14-5

6 Creating a File Using Object Serialization All simple-type variables and strings are serializable. For variables of reference types, their types must be serializable. By default, array objects are serializable. However, if the array contains references to other objects, those objects may or may not be serializable. 14-6

7 Common Programming Error It is a logic error to open an existing file for output when the user wishes to preserve the file. The original file’s contents will be lost. 14-7


Download ppt "Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields."

Similar presentations


Ads by Google