65.9K
CodeProject is changing. Read more.
Home

Hash Table and Serialization in .NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (11 votes)

Jul 8, 2002

1 min read

viewsIcon

176154

downloadIcon

1525

This article introduces hash table and serialization in .NET

Sample Image - Phonebook.jpg

Introduction

This article introduces and describes the use of hash table and serialization in .NET using C#. The sample application used here is a Phone Book application. Phone Book application is a console application that allows a user to add, view, list, and delete entries containing names and phone numbers.

A hash table is a collection of key-value pairs. In .NET, the class that implements a hash table is the Hashtable class. Elements can be added to the hash table by calling the Add method passing in the key-value pairs that you want to add. The objects used as keys must implement Object.Equals and Object.GetHashCode methods.

private Hashtable table = new Hashtable();
		
public void AddEntry(BookEntry entry)
{
   table.Add( entry.GetPerson(), entry );
}	

Once the hash table is populated, you can search and retrieve elements in it by calling the indexer for the Hashtable class.

public BookEntry GetEntry(Person key)
{
   return (BookEntry) table[key];
}			

Entries can be removed from the hash table by calling the Remove method which takes a key identifying the element you want to remove.

public void DeleteEntry(Person key)
{
   table.Remove( key );
}	

The populated hash table can be saved to a file by using serialization. Serialization is the process of converting an object into a linear sequence of bytes for either storage or transmission to another location. This task can be performed using BinaryFormater class which serializes the hash table object to the file stream.

public void Save()
{
   Stream s = File.Open("Phone.bin", FileMode.Create, FileAccess.ReadWrite);
   BinaryFormatter b = new BinaryFormatter();
   b.Serialize(s, table);
   s.Close();      
}		

The hash table object can be recovered back from the file by using Deserialize method as shown below.

    s = File.Open("Phone.bin", FileMode.Open, FileAccess.Read);
    BinaryFormatter b = new BinaryFormatter();
    table = (Hashtable) b.Deserialize(s);

I hope you enjoy this brief introduction on hash table and serialization in .NET.