Generic type of Generic Type in Powershell

Viewed 10914

Well generics in Powershel are quite confusing. To instantiate a simple List you need to dance around with a tambourine:

$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)

But what if I need something a bit more complex like: <Dictionary<string,List<Foo>> for example

or for example here: Dictionary<string,List<string>>

$listType = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$listType = $listType.MakeGenericType("System.string" -as "Type")
$L = [Activator]::CreateInstance($listType)

$dicType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"

#the next line is problematic
$dicType = $dicType.MakeGenericType( 
     @( ("system.string" -as "Type"), 
        ("System.Collections.Generic.List" as "Type)) # and that's of course wrong
      )

$D = [Activator]::CreateInstance($dicType )
5 Answers

I know this is perhaps a bit old, but this workaround appears to work nicely in PowerShell 2 and can pretty much be used as a direct replacement.

$foo = [activator]::CreateInstance(([System.Collections.Generic.List[string]] -as 'Type'))

Weird. I've always just done like this:

$dict = [system.collections.generic.dictionary[string, int]]::new()

$dict.add("my string", 42)

I always thought it was odd seeing people use New-Object and other unnecessary stuff when the constructor overloads are all exposed in a much more convenient way.

Though I only started with PS 3.0, admittedly.

Related