| Top Tips Subject: | Object Serialization |
| Difficulty: | Intermediate |
| Summary: | Object Serialization is the process of saving an instance of an object to a stream. This article will describe how you can implement serialization in your application to save the instance of a class to file and retrieve it later. |
Object Serialization, to put it in simple wording, is the process of saving the instance of an object to a stream. It differs from XML Serialization because the output is in binary (not entirely human readable) format. It is also much easier to implement.
In this tutorial I will teach you how to use serialization to store some settings to disk and retrieve them again. Below you will find the source code for the example class Settings, which has some members that can be read and written. This class can be used to store and retrieve settings while an application is running. When the user has changed some settings, you generally will want to store those changes and retrieve them when the user starts the application the next time.
I've created three different members. One that returns a Font object, another that returns a Color object and the last one returns a string. I did this on purpose to illustrate that you can serialize a variety of objects and not just textual data.
If you look at the code for the Settings class, you will notice that I added the [Serializable()] attribute to the class. This tells the interpreter that this class can be serialized. By default, all members of a serializable class will be serialized.
To implement serialization you need to write two methods in the form or class that takes care of the settings. The next portion of code is the code of a form with two methods: LoadSettings() and SaveSettings(). It also has a member settings of type Settings; the class we wrote earlier.
The methods for loading and saving settings are not yet implemented. The FileStream object fStream and the BinaryFormatter object bFormatter are used in these methods to open a file and read or write the settings.
Let's write code to implement the LoadSettings() method. This method needs to open the settings file and read the settings. We instantiate the fStream object first to accomplish this:
fStream = new FileStream(settingsFilename, FileMode.Open, FileAccess.Read, FileShare.None); |
This will open the file as defined in the string settingsFilename with file mode open, read only access and we define that the file is not shared at all. This will prevent any application, including this application, to open the file for another process until we close it first.
Next we instantiate the bFormatter and call its Deserialize() function to get the settings.
bFormatter = new BinaryFormatter(); settings = (Settings)bFormatter.Deserialize(fStream); |
The Deserialize() function has some overloaded versions, but we use the one that takes a stream to read from. The Deserialize() function returns an object that must be cast to its original type to be of any use. Since we know the type of the object we can cast it directly to Settings and assign it our settings object.
This is the basic code needed to deserialize an object that was serialized earlier. You are advised to wrap the code into a try...catch block to make it more safe. Below is the finished code for the LoadSettings() method.
In case a FileNotFoundException is thrown, we can use the catch block to set the default settings without having to let the user know about an exception being thrown. This also prevents the case that the settings file must be present in order for the application to work.
All we need now is the SaveSettings() method to save the settings when needed. We use the fStream object again to open the settings file, but this time for writing.
fStream = new FileStream(settingsFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); |
We instantiate the bFormatter object and use the Serialize() method to save our settings object to file.
bFormatter = new BinaryFormatter(); bFormatter.Serialize(fStream, settings); |
That is all there is to it. Let's finish the SaveSettings() method by making it safe.
You should of course modify the way I handled a general exception in both methods, but I will leave that up to you.
There are some problems you might run into using serialization:
- What if you don't want certain members of a class to be serialized?
You can prevent a member from being serialized by assigning the [NonSerializable()] attribute. - What if a return type is not declared Serializable?
If a member of your serializable class cannot be serialized (a SerializationException is thrown) then you can make it serializable by inheriting the object and implementing the ISerializable interface. This is a complicated subject, which may need a tutorial on its own. If you need help doing this I can assist. - Object instances can only be deserialized by the same assembly it was serialized with. This is a minor disadvantage since you cannot use the same settings file for multiple assemblies using the same classes.
Thank you for reading this DonationCoder Top Tips article! I hope it was useful to you.











Logged









).