-1

Method ToArray() is listed in .NET Framework reference but I can't access it in Powershell. Why? Are there alternatives?

EDIT:

Now I realize it's because I tried to add a value to the list with += as if it were an array. I wonder why it didn't work (help appreciated).

$test=New-Object -TypeName System.Collections.Generic.List[byte]
$test.Add(1)
$test.Add(2)
$test+=3
# NO $test.ToArray() METHOD (BECUASE OF $test+=3)`
  • 2
    Perhaps you could add code examples of what you've tried and a brief description of how it fails – Mathias R. Jessen Aug 14 '18 at 19:49
  • @MathiasR.Jessen - considering the OP's title is regarding generics, I assumed the issue is referring to the (static) Extension [Enumerable.ToArray](https://msdn.microsoft.com/en-us/library/bb298736(v=vs.110).aspx) method, which is not available, [as you pointed out in the comments here](https://stackoverflow.com/q/43883071/604196). – kuujinbo Aug 14 '18 at 19:58
  • @kuujinbo _Extension methods_ won't resolve, but as OP alludes, `ToArray()` is implemented as part of the `List` type definition itself – Mathias R. Jessen Aug 15 '18 at 07:51
  • 1
    "*7.7.3 Array concatenation: When the left operand designates an array the binary + operator creates a new unconstrained 1 dimensional array that contains the elements designated by the left operand followed immediately by the value(s) designated by the right operand.*" - Windows PowerShell Language Specification version 3.0.docx. Because when you used `+=` the type of the result changed from `[List[T]]` to `[array]` – TessellatingHeckler Aug 16 '18 at 00:38
  • Ahh there's an open issue about it: https://github.com/PowerShell/PowerShell/issues/5805 – TessellatingHeckler Aug 16 '18 at 01:51

1 Answers1

3

I was not able to reproduce the situation you described.

$foo=[system.collections.generic.list[string]]::new()
$foo.Add("A")
$foo.Add("B")
$foo.Add("C")
[string[]]$bar=$foo.ToArray()
$bar.GetType().FullName

"System.String[]"

Jake H
  • 1,720
  • 1
  • 12
  • 13