What is the need for Hash Table and Serialization in .Net ?

 Posted by Bharathi Cherukuri on 1/30/2012 | Category: ASP.NET Interview questions | Views: 5304 | Points: 40
Answer:

The Hashtable object contains items in key/value pairs. The keys are used as indexes. We can search value by using their corresponding key.
In .NET, the class that implements a hash table is the Hashtable class.

By using Add Method we can add elements to the Hashtable as shown below:

private Hashtable table = new Hashtable();


public void AddEntry(BookEntry entry)
{
table.Add( entry.GetPerson(), entry );
}

Once the Hashtable gets populated,you can search and retrieve data in it by calling the indexer for the Hashtable class as shown below:

public BookEntry GetEntry(Person key)

{
return (BookEntry) table[key];
}

You can also remove the records from the Hashtable by calling the Remove Method which takes a key identifying the element you want to remove as shown below:

public void DeleteEntry(Person key)

{
table.Remove( key );
}

The data populated from the Hashtable can be saved using Serialization process.
Serialization is a process where the object gets converted into a linear sequence of Bytes for storage or transmission to another location.
This process can be done by using BinaryFormater class which serializes Hashtable object to 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();
}


By using the Deserialize method, you can get back the recovered Hashtable object as shown below:

s = File.Open("Phone.bin", FileMode.Open, FileAccess.Read);

BinaryFormatter b = new BinaryFormatter();
table = (Hashtable) b.Deserialize(s);


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Chvrsri on: 1/30/2012 | Points: 10
Nice Post !! Keep posting !!!
Posted by: Bharathi Cherukuri on: 1/30/2012 | Points: 10
Hi Chvsri
Thank you..

Posted by: Akiii on: 1/31/2012 | Points: 10
Nice topic...

Thanks and Regards
Akiii
Posted by: Bharathi Cherukuri on: 2/2/2012 | Points: 10
Hi Akiii
Thanks..

Login to post response

More Interview Questions by Bharathi Cherukuri