views:

163

answers:

2

I have a simple function that creates a generic List:

function test()
{
    $genericType = [Type] "System.Collections.Generic.List``1"
    [type[]] $typedParameters = ,"System.String"
    $closedType = $genericType.MakeGenericType($typedParameters)
    [Activator]::CreateInstance($closedType)
}

$a = test

The problem is that $a is always null no matter what I try. If I execute the same code outside of the function it works properly.

Thoughts?

+2  A: 

An easier way to work with generics. This does not directly solve the [Activator] approach though

Function test
{
    New-Object "system.collections.generic.list[string]"
}

(test).gettype()
Doug Finke
+1  A: 

IMHO that's pitfall #1. If you return an object from the function that is somehow enumerable (I don't know exactly if implementing IEnumerable is the only case), PowerShell unrolls the object and returns the items in that.

Your newly created list was empty, so nothing was returned. To make it work just use this:

,[Activator]::CreateInstance($closedType)

That will make an one item array that gets unrolled and the item (the generic list) is assigned to $a.

Further info

Here is list of similar question that will help you to understand what's going on:


Note: you dont need to declare the function header with parenthesis. If you need to add parameters, the function will look like this:

function test {
 param($myParameter, $myParameter2)
}

or

function  {
param(
  [Parameter(Mandatory=true, Position=0)]$myParameter,
  ... again $myParameter2)
...
stej
The comma! D'oh. Thanks, I'll get that right one of these days.
Dan