Search code examples
powershellienumerable

Create a PowerShell Collections.Generic.IEnumerable[string] error


I can't create an IEnumerable on PowerShell.

My goal is another issue/type, but help me solve this "simple" one.

C:\Users\Me> $var = New-Object Collections.Generic.IEnumerable[string]
New-Object : A constructor was not found. Cannot find an appropriate constructor for type Collections.Generic.IEnumerable[string].
At line:1 char:8
+ $var = New-Object Collections.Generic.IEnumerable[string]
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

Can anyone clarify where or what I'm doing wrong?

The final object have a property with Collections.Generic.IEnumerable[...] so that is why using this type.


Solution

  • IEnumerable[TypeParameter] is an interface, an abstract type that cannot be instantiated.

    If you want an instance of a generic collection that implements IEnumerable[string], create a List[string]:

    $var = New-Object System.Collections.Generic.List[string]
    

    If you use PowerShell 5.0 and newer versions' ::new() method, you can skip the System namespace prefix:

    $var = [Collections.Generic.List[string]]::new()
    # these will resolve to the same type
    $var = [System.Collections.Generic.List[string]]::new()