We begin by creating and writing serialized objects to a sequential-access file. In this section, we reuse much of the code from Section 17.3, so we focus only on the new features.
RecordSerializable
ClassLet’s modify class Record
(Fig. 17.3) so that objects of this class can be serialized. Class RecordSerializable
(Fig. 17.8; part of the BankLibrary
project) is marked with what is-known as an attribute—[Serializable]
(line 7)—this attribute indicates to the CLR that RecordSerializable
objects can be serialized. Classes that represent serializable types must include this attribute in their declarations or must implement interface ISerializable
.
In a class that’s marked with the [Serializable]
attribute or that implements interface ISerializable
, you must ensure that every instance variable of the class is also serializable. All simple-type variables and string
s are serializable. For variables of reference types, you must check the class declaration (and possibly its base classes) to ensure that the type is serializable. By default, array objects are serializable. However, if the array contains references to other objects, those objects may or may not be serializable.
Next, we’ll create a sequential-access file with serialization (Fig. 17.9). To test this program, we used the sample data from Fig. 17.5 to create a file named clients.ser
—we chose the extension .ser
to indicate that the file stores serialized objects. Since the sample screen captures are the same as Fig. 17.4, they are not shown here. Line 15 creates a BinaryFormatter
for writing serialized objects. Lines 55–56 open the FileStream
to which this program writes the serialized objects. The string
argument that’s passed to the FileStream
’s constructor represents the name and path of the file to be opened. This specifies the file to which the serialized objects will be written.
This program assumes that data is input correctly and in record-number order. Method enterButton_Click
(lines 73–120) performs the write operation. Lines 92–95 create and initialize a RecordSerializable
object. Line 98 calls Serialize
to write the RecordSerializable
object to the output file. Method Serialize
takes the FileStream
object as the first argument so that the BinaryFormatter
can write its second argument to the correct file. The app does not specify how to format the objectfor output—Serialize
handles these details. If a problem occurs during serialization, a SerializationException
occurs.
In the sample execution (Fig. 17.9), we entered five accounts—the same as in Fig. 17.5. The program does not show how the data records actually appear in the file. Remember that we are now using binary files, which are not human readable. To verify that the file was created successfully, the next section presents a program to read the file’s contents.