41

Given this powershell code:

$drivers = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$drivers.Add("nitrous","vx")
$drivers.Add("directx","vd")
$drivers.Add("openGL","vo")

Is it possible to initialize this dictionary directly without having to call the Add method. Like .NET allows you to do?

Something like this?

$foo = New-Object 'System.Collections.Generic.Dictionary[String,String]'{{"a","Alley"},{"b" "bat"}}

[not sure what type of syntax this would involve]

dreftymac
  • 29,742
  • 25
  • 114
  • 177
C Johnson
  • 15,085
  • 9
  • 58
  • 75

2 Answers2

75

No. The initialization syntax for Dictionary<TKey,TValue> is C# syntax candy. Powershell has its own initializer syntax support for System.Collections.HashTable (@{}):

$drivers = @{"nitrous"="vx"; "directx"="vd"; "openGL"="vo"};

For [probably] nearly all cases it will work just as well as Dictionary<TKey,TValue>. If you really need Dictionary<TKey,TValue> for some reason, you could make a function that takes a HashTable and iterates through the keys and values to add them to a new Dictionary<TKey,TValue>.


The C# initializer syntax isn't exactly "direct" anyway. The compiler generates calls to Add() from it.

Joel B Fant
  • 23,966
  • 4
  • 65
  • 67
  • I don't really need dictionary. A .NET hash table will work just fine. – C Johnson Jul 20 '11 at 17:13
  • 2
    It's worth noting that [a HashTable and a Dictionary do have differences](https://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable), but that those differences will largely be considered not relevant for common PowerShell scripting. – Bacon Bits Oct 09 '17 at 12:59
1

For those who like to really use Dictionary. In my case I had to use another c# dll which has a dictionary as parameter:

New-Object System.Collections.Generic.Dictionary"[String,String]"

This was probably not possible back in 2011

Gideon Mulder
  • 334
  • 3
  • 6