Justin Dearing
Justin Dearing

Reputation: 14928

Making a List<T> of a type created via Add-Type -TypeDefinition in powershell

I have a class that I define in inline C# in powershell:

Add-Type -TypeDefinition @"
    public class SomeClass {
        string name;
        public string Name { get { return name; } set { name = value; } }
        int a, b;
        public int A { get { return a; } set { a = value; } }
        public int B { get { return b; } set { b = value; } }
    }
"@

I can instantiate it: $someClass= New-Object SomeClass -Property @{ 'Name' = "Justin Dearing"; "A" = 1; "B" = 5; };

But I cannot instantiate a list of it:

$listOfClasses = New-Object System.Collections.Generic.List[SomeClass];

Doing so gets me the following:

New-Object : Cannot find type [[System.Collections.Generic[SomeClass]]]: make sure the assembly containing this type is loaded.
At line:12 char:28
+ $listOfClasses = New-Object <<<<  [System.Collections.Generic[SomeClass]]
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

Upvotes: 3

Views: 1814

Answers (3)

Justin Dearing
Justin Dearing

Reputation: 14928

One solution is to simple make a List<SomeClass> factory in the SomeClass definition like so:

Add-Type -TypeDefinition @"
    using System.Collections.Generic;

    public class SomeClass {
        string name;
        public string Name { get { return name; } set { name = value; } }
        int a, b;
        public int A { get { return a; } set { a = value; } }
        public int B { get { return b; } set { b = value; } }

        public static List<SomeClass> CreateList () { return new List<SomeClass>(); }
    }
"@

Then you can instantiate a list like so $listOfClasses = [SomeClass]::CreateList();

Upvotes: 0

driis
driis

Reputation: 164291

It seems that is not directly supported in PowerShell. Here is a solution, which provides a New-GenericObject script; that does some reflection in order to create the correct type.

Upvotes: 2

Related Questions