Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in PowerShell 2 not working?

How could I make a List in PowerShell 2? I've tried these:

[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

and

[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

and all I get is just nothing. What's going wrong?

I'm running XP SP3, if it matters

like image 753
Parsa Avatar asked Jan 21 '10 13:01

Parsa


Video Answer


2 Answers

Try this:

PS> $list = New-Object 'System.Collections.Generic.List[string]'
PS> $list.Add('foo')
PS> $list
foo

PS> $d = New-Object 'System.Collections.Generic.Dictionary[string,datetime]'
PS> $d.Add('moonshot', [datetime]'7/20/1969')
PS> $d['moonshot']

Sunday, July 20, 1969 12:00:00 AM
like image 120
Keith Hill Avatar answered Sep 23 '22 13:09

Keith Hill


If you try to create a list based on strings, try this:

New-Object 'System.Collections.Generic.List[system.string]'

Note that you have to specify 'system.string' (at least on my comp ;) ). If you just use 'string', it throws an exception.

[61]: New-Object 'System.Collections.Generic.List[string]'
New-Object : Cannot find type [System.Collections.Generic.List[string]]: make sure the assembly containing this type is loaded.
At line:1 char:11
+ New-Object <<<<  'System.Collections.Generic.List`1[string]'
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
like image 42
stej Avatar answered Sep 22 '22 13:09

stej