What is the difference between Dictionary and HashTable in PowerShell?


PowerShell programmers generally prefer the Hashtable over the Dictionary although there are some advantages of using Dictionary. See the difference below.

a. Hashtable is easy to declare while the Dictionary is a little complex compared to Hashtable. For example,

To create a hashtable,

$hash = @{
   'Country' = 'India'
   'Code' = '91'
}

To create a Dictionary,

$citydata = New-Object System.Collections.Generic.Dictionary"[String,Int]"
$citydata.Add('India',91) 

b. Hashtable is included in the namespace called Collections while Dictionary is included in the namespace called System.Collections.Generic namespace. Hashtable is non-generic so it can be a collection of different data types and Dictionary belongs to a generic class so it is a collection of specific data types.

c. Hashtable and Dictionary both have the BaseType is Object but their datatypes are different. Hashtable has a ‘Hashtable’ datatype and Dictionary has a Dictionary`2 datatype.

Hashtable:

IsPublic IsSerial Name      BaseType
-------- -------- ----      --------
True     True     Hashtable System.Object

Dictionary:

IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Dictionary`2 System.Object

Updated on: 15-Dec-2020

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements