You are here:About>Computing & Technology>Visual Basic
About.comVisual Basic
Visual Basic .NET for Beginners
Serialization ... What is it?
 More of this Feature
• Part 1: The Lesson Goals
• Part 3: XML Serialization
• Part 4: The Completed Program
 
 Join the Discussion
Log into the About VB Forum Here!
 
 Elsewhere on the Web
• Get the .NET Framework SDK
• The Visual Studio Icons Explained
 

In brief, serialization is the process of converting an object into a linear sequence of bytes.

Remember that an object is just a software "black box". But since it's software, it's also a sequence of coding instructions and data.

A byte is a short for "binary digit" and demonstrates how well nerds can spell. It's roughly the same as a single character. A linear sequence of bytes is usually called a byte stream in programming.

But why would you want to convert an object into a byte stream?

The reason is so you can move the object around. Consider the possibilities. In the first lesson, we learned that in .NET "everything is an object". So you could serialize pictures, data files, the current state of a program module ('state' is like a snapshot of your program at a point in time so you could temporarily suspend execution and start again later) ... whatever your system is doing. And you can store these objects on disk, send them over the web, pass them to a different program, keep a backup copy for safety or security. The possibilities are quite literally endless. In fact, the main reason programmers don't use serialization more is that a lot of them don't know about it. Starting now, that is a group that you are not a member of.

Serializing an Object

VB.NET gives you a number of ways to do this, so we're going to create our application in careful stages to show you some of the options as we go.

One very important point: All of our code will be a Console Application so you can use any of our 'cheap' methods to create the same system on your computer. This program must be executed at the Command Line. If you don't understand what this is, go back and read Lesson 2 again.

There are some 'object management tasks' - making sure the VB.NET compiler and your program can find the objects in .NET that they need - that will be explained at the very end of this lesson. These subroutines won't run by themselves, but we'll look at how to put them together into a working program using only the Visual Basic .NET SDK before we're finished.

The first stage is to create the object that we will serialize. In VB.NET, objects are represented in code by a Class. Here's the class we will use:

<Serializable()> Public Class VBLesson
    Public LessonTitle As String
    Public LessonNumber As Int16
End Class

We'll place this class in a module for easy reference in our code later.

First, notice that this is just an empty shell at this time. There isn't any data, just a descripion of what the data will be. We'll add the data later too.

And notice too that the Class is marked with the <Serializable()> attribute. Attributes are an XML idea that is used a great deal more in VB.NET. You can read the About Visual Basic explanation of attributes here. The <Serializable()> attrbute tells VB.NET to add the code necessary to convert our object into a byte stream.

Next, the actions of our program will be explained. A lot of new words and programming statements are going to be used all at once, but just think of them as "black box" objects (I do!) and trust that they do what they're supposed to do. You have Microsoft's word on it!

To make it easier to follow, the code below has numbers to the left of the statements so you can see which statements correspond to the steps below. Don't forget to take these numbers out again if you copy the code from the web page!

Using a subroutine (see the code below), we ...

  1. Create a new instance of a Collection Object - in this case an ArrayList object - to hold our data.
  2. Create a new instance of our serializable VBLesson object.
  3. Put some data into our Collection object and add each element into the array.
  4. Create an instance of the FileStream object used to write the serialized object to a file and create the file.
  5. Incidentally, this same FileStream object could be used to create a simple file as well.

  6. Create an instance of the BinaryFormatter object that actually does the work of serializing our object.
  7. First, we're going to create a binary file rather than an XML file - mainly to illustrate the difference for you. We'll create an XML file next.

  8. Serialize the object into the file! (Wow! At last!)
  9. And then close the file.
  10. Note that Serialize is actualy a method of the BinaryFormatter object that takes the FileStream object and the object to be serialized as parameters.

Sub SaveSerializedFile()
1   Dim LessonList As New ArrayList
2   Dim LessonInfo As New VBLesson

3   LessonInfo.LessonTitle = "Why did they break VB?"
3   LessonInfo.LessonNumber = 1
3   LessonList.Add(LessonInfo)

3   LessonInfo = New VBLesson
3   LessonInfo.LessonTitle = "VB.NET in Three Acts"
3   LessonInfo.LessonNumber = 2
3   LessonList.Add(LessonInfo)

3   LessonInfo = New VBLesson
3   LessonInfo.LessonTitle = "You're Not a Beginner Anymore!"
3   LessonInfo.LessonNumber = 3
3   LessonList.Add(LessonInfo)

4   Dim s As New FileStream("lessoninfo.txt", FileMode.Create)
5   Dim f As New BinaryFormatter
6   f.Serialize(s, LessonList)
7   s.Close()
End Sub

binary serialized object Now, let's see what we have in our output file, lessoninfo.txt. Remember that this file will contain not only the data from our object, but the entire object! The file is designed for flexibility and efficiency of serialization using the .NET objects. It's not designed to be read by anything except other programs. So much of the content is (naturally) binary data that won't mean anything to you. But it's instructive to look at it with a generic file viewer, like Notepad.

The actual character strings of all of the array elements show up very clearly, as does everything else in the ArrayList object. The LessonNumber values can't be seen directly in Notepad since they're binary numbers (Int16 or short integer) variables.

Since the purpose of serialization is usually to save the object for use sometime later, we need to write a short program to do that next. For this, we use the Deserialize method of the same BinaryFormatter object. Here's the code, along with some additional code to actually display the data using another ArrayList object just to prove that the object really was restored.
(No tricks ... nothing up my sleeve ...)



Sub RestoreSerializedFile()
    Dim s = New FileStream("lessoninfo.txt", FileMode.Open)
    Dim f As BinaryFormatter = New BinaryFormatter
    Dim RestoredLessonList As ArrayList
    RestoredLessonList = CType(f.Deserialize(s), ArrayList)
    s.close()
    Dim x As VBLesson
    For Each x In RestoredLessonList
        Console.WriteLine(x.LessonTitle & _
            " Lesson Number " & x.LessonNumber)
    Next
    Console.WriteLine("Press Enter to Continue ...")
    Console.ReadLine() ' To force a pause in the program
End Sub

DOS OutputThe output from simply calling both subroutines is shown at left.

Next page > XML Serialization > Page 1, 2, 3, 4

From Dan Mabbutt,
Your Guide to Visual Basic.
FREE Newsletter. Sign Up Now!
Newsletters & RSSEmail to a friendSubmit to Digg
 All Topics | Email Article | | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.