Strongly Typed Arrays

by Nov 11, 2010

When you assign strongly typed values to an array, the type declaration will remain intact only as long as you do not add new array content:

$array = [Int[]](1,2,3,4,5)
$array.GetType().FullName
System.Int32[]
$array += 6
$array.GetType().FullName
System.Object[]

Once you add new content using +=, the complete array will be copied into a new one, and type information is lost. You can work around this by simply strongly type the variable that stores the array instead:

[Int[]]$array = 1,2,3,4,5
$array.GetType().FullName
System.Int32[]
$array += 6
$array.GetType().FullName
System.Int32[]

As you can see, the type information is preserved this way.

Twitter This Tip!
ReTweet this Tip!