Friday, October 10, 2014

Difference Between HashTable and Dictionary in C#

Both HashTable and Dictionary stores values in form of Key-Value pairs,To access the values from Hash Table or from Dictionary we use Key to get value.But their are other difference between HashTable and Dictionary shown below.

HashTable :

  • Hash table is not a generic type.
  • Hashtable is a collection of data structures to hold data as key-value pairs.
  • The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable.
  • In Hashtable boxing/unboxing (valuetypes need boxing) will happened and which may have memory consumption
  • When we add values to HashTable the order of values is not maintained while retrieving.
Declarartion:

Hashtable numbers = new Hashtable();

Dictionary:

  • Dictionary is a generic type.
  • Dictionary is a collection of data structures to hold data as key-value pairs.
  • The Dictionary is a strongly typed data structure, so you should specify the data types for both the key and value < T Key, T Value >.
  • In Dictionary boxing/unboxing (valuetypes need boxing) will not happened 
  • When we add values to Dictionary the order is maintained while retrieving
Declarartion:
Dictionary<int, string> dictionary = new Dictionary<int, string >();


I will explane clearly with example
Step1: Create one page in web application and design page add following code in form tag  of page
<div>
<table>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="BindValuesToDropDown" OnClick="Button1_Click" />
</td>
</tr>
<tr>
<td>Bind with HashTable:</td>
<td>Bind with Dictionary:</td>
</tr>
<tr>
<td><asp:DropDownList runat="server" ID="ddlHashTable"></asp:DropDownList></td>
<td><asp:DropDownList runat="server" ID="ddlDictionary"></asp:DropDownList></td>
</tr>
</table>
</div>

Page looks like shown below


.Step2: Add following code in Button Click Event .cs page

 protected void Button1_Click(object sender, EventArgs e)
    {
        Hashtable hashtable = new Hashtable();
        hashtable.Add(1, "one");
        hashtable.Add(2, "two");
        hashtable.Add(3, "three");
        hashtable.Add(4, "four");
        hashtable.Add(5, "five");

        ddlHashTable.DataSource = hashtable;
        ddlHashTable.DataTextField = "key";
        ddlHashTable.DataValueField = "value";
        ddlHashTable.DataBind();

        Dictionary<int, string> dictionary = new Dictionary<int, string>();
        dictionary.Add(1, "one");
        dictionary.Add(2, "two");
        dictionary.Add(3, "three");
        dictionary.Add(4, "four");
        dictionary.Add(5, "five");
        ddlDictionary.DataSource = dictionary;
        ddlDictionary.DataTextField = "key";
        ddlDictionary.DataValueField = "value";
        ddlDictionary.DataBind();
       
    }

Step 3: Final Output get like these









No comments:

Post a Comment