Create an array, hashtable and dictionary?

Powershell

Powershell Problem Overview


What is the proper way to create an array, hashtable and dictionary?

$array = [System.Collections.ArrayList]@()

$array.GetType() returns ArrayList, OK.

$hashtable = [System.Collections.Hashtable]

$hashtable.GetType() returns RuntimeType, Not OK.

$dictionary = ? 

How to create a dictionary using this .NET way?

What is the difference between dictionary and hashtable? I am not sure when I should use one of them.

Powershell Solutions


Solution 1 - Powershell

The proper way (i.e. the PowerShell way) is:

Array:

> $a = @()
> $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Hashtable / Dictionary:

> $h = @{}
> $h.gettype()

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

The above should suffice for most dictionary-like scenarios, but if you did explicitly want the type from Systems.Collections.Generic, you could initialise like:

> $d = New-Object 'system.collections.generic.dictionary[string,string]'
> $d.gettype()

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

> $d["foo"] = "bar"
> $d | Format-Table -auto

Key   Value
---   -----
foo   bar

Solution 2 - Powershell

If you want to initialize an array you can use the following code:

$array = @()    # empty array
$array2 = @('one', 'two', 'three')   # array with 3 values

If you want to initialize hashtable use the following code:

$hashtable = @{}   # empty hashtable
$hashtable2 = @{One='one'; Two='two';Three='three'}   # hashtable with 3 values

Hashtable and dictionary in Powershell is pretty much the same, so I suggest using hashtable in almost all cases (unless you need to do something in .NET where Dictionary is required)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionexpirat001View Question on Stackoverflow
Solution 1 - Powershellarco444View Answer on Stackoverflow
Solution 2 - PowershelldotnetomView Answer on Stackoverflow