Click here to Skip to main content
Click here to Skip to main content

Hashtable becomes serialized

, 21 Oct 2002
Rate this:
Please Sign up or sign in to vote.
How to create a hashtable, use it, and serialize/deserialize it.

Introduction

In this article you will see how easy it is to use a hashtable to save and retrieve data, and you will also see how easy it is to serialize the hashtable to a binary file, for later loading.

A hashtable is a data structure that provides couple of major improvements when compared with others, like linked list, or basic array. A hashtable provides a way to insert/take out elements from the the data structure by using a key/value pair. a key value pair means that your data is divided into a key data and a value data, when the key is a unique ID, and the data may or may not be repeatable. While using this technique, you must first, before head for coding, set your data structure needs on the table.

The sample code creates a demo of a phone book, the phone book holds a name against address, like a real phone book, where you open and look for a name first, and the name gives you the number. so in our example the Key which must be unique is the name (actually it can be a unique object, and we will use a name struct with first name and last name). our value will be the address, which is also a struct, that will hold street name and number.

[Serializable]
struct name
{
  public string forname;
  public string familyname;
}

[Serializable]
struct address
{
  public string street;
  public int number;
}

We will get to the[Serializable] attribute in a second.

now we need to create a hashtable, and assign it the objects, or read objects from it, for example, in the provided example there is a method that adds an object to the hashtable: AddNew()

public void AddNew()
{
    name nm; //name struct
    address ad; //address struct
    string ans; //answer string

    //we then ask info from the user and insert that info to our structs
    System.Console.WriteLine ("enter first name (x to exit):");
    ans = System.Console.ReadLine();
    nm.forname = ans;
    System.Console.WriteLine ("enter last name (x to exit):");
    ans = System.Console.ReadLine();
    nm.familyname = ans;
    System.Console.WriteLine ("enter street name (x to exit):");
    ans = System.Console.ReadLine();
    ad.street = ans;
    System.Console.WriteLine ("enter street number (x to exit):");
    ans = System.Console.ReadLine();
    ad.number = int.Parse (ans);

    //now we save the new object into the hashtable, 
        //the key here is the name struct
    NameToAddress.Add(nm,ad);
}

The method used here is Add on the hashtable, another approach that could be used is index based insertion:

NameToAddress[nm]=ad;

the difference between the two is that the first one is looking that it is not overwriting another key, remember we talked about unique keys, a key is assigned to a value, and we want to assign the struct name (nm) with the struct address (ad) and use nm as the key, if we have created a second user name with the same name and last name, the key is considered to be the same and not unique, by using the Add method on the hashtable and giving it a already hashed key, an exception is thrown. while using the index based, any key that is the same, is being overwritten, if it is not available is is being created.

setting new items is not enough, we also want to save the data to a file, in order to exit the application and load the hashtable later. the code includes a save method and a load method, notice in the code that the two structs we are using are marked as serializable, this gives the C# compiler a head start, on setting the needed fields for serialization. in order to serialize we use a file stream, and a binary formatter, the file stream is for opening/overwriting a file, and the binary formatter is for the actual serialization. for example the save code:

public void Save()
{
    //file stream states the saved binary
    FileStream fs = new FileStream   
                   ("Store.dat",FileMode.OpenOrCreate ,FileAccess.Write );
            
        try
    {
    Hashtable a = new Hashtable();
    a = NameToAddress;
    BinaryFormatter bf=new BinaryFormatter ();
    //as easy as 1,2,3...we serialize a to a binary <BR>    //formating using file stream.
    bf.Serialize (fs,a );
    }
    finally
    {
    fs.Close ();
    }
}

We use here a file stream that opens a file for writing, we also set it to create if not available, next we create a binary formatter which is a class that the .net gives us to make serialization easy, and use the Serialize method giving the file, and the object, remember that any object could be serialized. later when we would like to deserialize the saved binary file, we just need to open it, use a binary formatter and DeSerialize it.

The entire code example is self explainable, open it, look at it and compile it as a console application.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

sagivh
Web Developer
Europe Europe
No Biography provided

Comments and Discussions

 
QuestionDeserializing question PinmemberPACO7716-Aug-07 22:39 
GeneralThanks! Pinmemberbneacetp7-Mar-07 5:39 
GeneralReally its superb Pinmembercoolcsharpguy13-Dec-05 20:15 
GeneralHashtable into an XML file PinmemberVictor Paraschiv20-Nov-05 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 22 Oct 2002
Article Copyright 2002 by sagivh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid