Reading Time: 1 minute

C sharp hashtable is very useful data structure in C#. Actually, it is kind of arraylist with two-dimensional Items. With this two-dimensional feature it can be very easy to define look-up table for different type of data such as string with integer. Namespace System.Collections must be included. Here is one C sharp hashtable example:

using System.Collections;

static void Main(st ring[] args)

Hashtable htCity = new Hashtable();
htCity.Add(19.5, “New York”);
htCity.Add(20.7, “Peking”);
htCity.Add(4.6, “Sidney”);
htCity.Add(0.9, “Naples”);
htCity.Add(11.3, “Sao Paolo”);
htCity.Add(15.5, “Cairo”);

All hashtable Members can be displayed with foreach loop, but we must be careful. Since items in hashtable are two dimensional (key and value), if we use foreach loop, we must use DictionaryEntry in foreach call.

foreach (DictionaryEntry obj in htCity)

Console.WriteLine(“key:{0} value: {1}”,obj.Key, obj.Value);


If, however, we would like to use either key or value, we can display results with foreach loop but with regular objects:

foreach (Object obj_key in htCity.Keys)

Console.WriteLine(“key:{0} “,obj_key);

foreach (Object obj_value in htCity.Values)

Console.WriteLine(“value:{0} “, obj_value);


If two-dimensional data are of the same type (let’s say integers or strings), then multidimensional array can do the same job as hashtable, but hashtable still has advantage that it is dynamically resizable.

External links:

C Sharp Hashtable Example on Dotnetperls
C Sharp Hashtable Example on Microsoft
C Sharp Hashtable Example on Homeandlearn
C Sharp Hashtable Example C-sharpcorner.com

Leave a Reply

Your email address will not be published. Required fields are marked *