How to create an instance of an generic class in PowerShell

Sometimes you may need to create instances of generic classes in PowerShell.

Like this (in C#):

 using  System;

 using  System.Text;
 namespace  tmp1
     class  Program 
         static  void  Main(string [] args)
             System.Collections.Generic.List<string> t = new  System.Collections.Generic.List<string>();

There is a generic class used in the code above: System.Collection.Generic.List.

If you want to create an instance of this class in PowerShell you can not use this:

New-Object "System.Collections.Generic.List<string>"

You’ll receive an error!

Here is the solution: You can use the System.Type that represents other .NET types.

Use this PowerShell code snipped to create an instance of System.Collections.Generic.List<string>

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

“$o” will contain the created instance.

You can use this method for all other generic classes.

You may need to change the following details.

  1. In the first line of the snipped there is `+"1" This is the amount of parameters for the generic class.
  2. In the second line you have to specify the parameter types for the generic class. Separate them with “,” and cast them to System.Type by using -as “Type”.
  3. In the third line you may need to specify the constructor parameters for creating an instance of the generic class.

Here is another example:

$type = ("System.Collections.Generic.SortedList"+'`'+"2") -as "Type"
$type = $type.MakeGenericType( @( ("System.Int32" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type, 100)
$o.Add(1, "test")

This creates an instance of System.Collections.Generic.SortedList<System.Int32, String> with a starting capacity of 10 (line 3: the second parameter of CreateInstance).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s