What is serialization ?

Say you have a class named myDog. You take the class myDog, along with all its properties, such as size and color, and persist it in a format that can be saved to a file or sent over a network. Its basically like taking a live dog, and saving it to a file. Of course you can also deserialize whats been serialized, essentially taking the file and turning it back into the class myDog. If youre further interested in the topic, youll discover both binary and XML serialization. Binary serialization can save an object to memory, save it to disk or send it over a network. XML serialization saves the object in a format that is human readable, such as the following:
Code:
<dog>
    <color>black</color>
    <size>4</size>
</dog>
Its a fairly useful technology. Learn more about it in MSDN:
ms-help://MS.VSCC/MS.MSDNVS/cpguide/html/cpovrserializingobjects.htm
 
I find it useful for file formats. Where before you might invent a file format for your program, read it line by line and parse it to create your class, now you just use a couple of lines to serialize an instance of the class to disk in XML format (or other).
 
Derek, I didnt know dogs had sizes... or is that supposed to be
its shoe size? :D
 
Speaking of serialization, Im having trouble serializing collections. Ive got a custom object that inherits an arraylist which is filled with custom objects, I can serialize the single object fine but the custom collection gives me the following exception. Any ideas?

An unhandled exception of type System.InvalidOperationException occurred in system.xml.dll

Additional information: There was an error generating the XML document.
 
Collections should serialize ok, dictionaries wont though. Read the docs on the xml serializers or search google, I found many resources on serializing collections when I had to do it.
 
Yep, I think Im doing what Ive read, and dumbed it down to be a fairly simple test. It has problems with any of my custom objects being in the arraylist.
Code:
Public Class Form1
    Inherits System.Windows.Forms.Form


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cfl As New ArrayList() 

        cfl.Add(New SimpleDate())


        cfl.TrimToSize()

        Dim ser As XmlSerializer = New XmlSerializer(GetType(ArrayList))
        Dim writer As TextWriter = New StreamWriter("adminSettings.xml")
        ser.Serialize(writer, cfl)
        writer.Close()

    End Sub
End Class


<Serializable()>Public Class SimpleDate
    Public SimpleDate As DateTime
End Class
 
Maybe the serializers only serialize public properties, and not fields? It would definitely be worth a try.
 
Thanks for the explanation. I think I understand the concept.

What is the purpose of the <serializable> tag I sometimes see on functions and subs?

p.s. I couldnt get that link to work
 
Back
Top