Search code examples
arrayspowershellcollectionstypescoercion

Array Types In Powershell - System.Object[] vs. arrays with specific types


Why does caling GetType().Name on an array of strings return Object[] and not String[]? This seems to happen with any element type, for example Import-Csv will give you an Object[] but each element is a PSCustomObject.

Here's an example with an array of String

$x = @('a','b','c')

$x[0].GetType().Name #String
$x.GetType().Name #Object[]

Solution

  • Because you have not specified the data type of the array explicitly.

    For instance, assigning an integer to $x[1] would work, because the array's type is Object[].

    If you specify a data type while constructing the array, you won't be able to assign values of an incompatible type later:

    C:\PS> [int[]] $myArray = 12,64,8,64,12
    
    C:\PS> $myArray.GetType()
    
    IsPublic IsSerial Name                                     BaseType                   
    -------- -------- ----                                     --------                   
    True     True     Int32[]                                  System.Array               
    
    
    
    C:\PS> $myArray[0] = "asd"
    Cannot convert value "asd" to type "System.Int32". Error: "Input string was not in a c
    orrect format."
    At line:1 char:1
    + $myArray[0] = "asd"
    + ~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastFromStringToInteger