Top Tips #1: Object Serialization in C# -
HOME | Blog | Software | Reviews and Features | Forum | Help | Donate
Click here to
donate and join now!
Welcome Guest.   Make a donation to an author on the site April 21, 2015, 03:19:57 AM  *

Please login or register.
Or did you miss your validation email?

Login with username and password (forgot your password?)
Why not become a lifetime supporting member of the site with a one-time donation of any amount? Your donation entitles you to a ton of additional benefits, including access to exclusive discounts and downloads, the ability to enter monthly free software drawings, and a single non-expiring license key for all of our programs.

You must sign up here before you can post and access some areas of the site. Registration is totally free and confidential.
The N.A.N.Y. Challenge 2011! Download 30+ custom programs!
   Forum Home   Thread Marks Chat! Downloads Search Login Register  
Pages: [1]   Go Down
  Reply  |  New Topic  |  Print  
Author Topic: Top Tips #1: Object Serialization in C#  (Read 13539 times)
Honorary Member
Posts: 332

Uhm yeah...

View Profile WWW Give some DonationCredits to this forum member
« on: January 31, 2007, 12:39:14 AM »

Welcome to the first of a series of Top Tips articles I intend to write. Top Tips articles will deal with a variety of subjects in different programming languages, ranging from beginner level to expert mode. Feel free to provide feedback by posting replies or sending me a message.

Top Tips Subject:Object Serialization
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.

Listing 1. The Settings class

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.

Listing 2. Preparing the form's code to load and save settings.

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);

Snippet 1. Initializing the file stream to read the settings.

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);

Snippet 2. Initializing the binary formatter and deserialize the stream.

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.

Listing 3. 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);

Snippet 3. Initializing the file stream for writing the settings.

We instantiate the bFormatter object and use the Serialize() method to save our settings object to file.

bFormatter = new BinaryFormatter();
bFormatter.Serialize(fStream, settings);

Snippet 4. Initializing the binary formatter and serialize the settings to the file stream.

That is all there is to it. Let's finish the SaveSettings() method by making it safe.

Listing 4. The SaveSettings() method.

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.


Programming is an art form that fights back.
Global Moderator
Posts: 4,724

Artificial Idiocy

see users location on a map View Profile WWW Read user's biography. Give some DonationCredits to this forum member
« Reply #1 on: January 31, 2007, 05:36:15 AM »

Now this is a fantastic idea!!
Thanks a lot for this article, Ruffnekk!
I suspect it'll be of huge interest for people using c#  Thmbsup

Honorary Member
Posts: 332

Uhm yeah...

View Profile WWW Give some DonationCredits to this forum member
« Reply #2 on: January 31, 2007, 05:40:44 AM »

Now this is a fantastic idea!!
Thanks a lot for this article, Ruffnekk!
I suspect it'll be of huge interest for people using c#  Thmbsup

Thank you jgpaiva  Thmbsup I'll try to post an article like this on a regular basis (not so regular intervals maybe Wink).


Programming is an art form that fights back.
Posts: 1

View Profile Give some DonationCredits to this forum member
« Reply #3 on: May 26, 2009, 02:12:36 AM »

Hi there,

You might also be interested in the NFileStorage codeplex project; it features a persistence framework that allows to serialize multiple objects/files/strings into a single container, and easily retrieve the information from there afterwards (all sources are included and its completely free). You can find it  Thmbsup

Pages: [1]   Go Up
  Reply  |  New Topic  |  Print  
Jump to:  
   Forum Home   Thread Marks Chat! Downloads Search Login Register | About Us Forum | Powered by SMF
[ Page time: 0.053s | Server load: 0.02 ]

Share on Facebook
submit to reddit