Click here to Skip to main content
6,594,932 members and growing! (14,607 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Data Structures     Intermediate

Hashtable becomes serialized

By sagivh

How to create a hashtable, use it, and serialize/deserialize it.
C#, Windows, .NET 1.0, Visual Studio, Dev
Posted:21 Oct 2002
Views:78,132
Bookmarked:30 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
20 votes for this article.
Popularity: 3.95 Rating: 3.04 out of 5
4 votes, 26.7%
1
2 votes, 13.3%
2
1 vote, 6.7%
3
7 votes, 46.7%
4
1 vote, 6.7%
5

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 
//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

About the Author

sagivh


Member

Occupation: Web Developer
Location: Europe Europe

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
QuestionDeserializing question PinmemberPACO7723:39 16 Aug '07  
GeneralThanks! Pinmemberbneacetp6:39 7 Mar '07  
GeneralReally its superb Pinmembercoolcsharpguy21:15 13 Dec '05  
GeneralHashtable into an XML file PinmemberVictor Paraschiv0:37 21 Nov '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Oct 2002
Editor: Nishant Sivakumar
Copyright 2002 by sagivh
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project