Write-Protected Arrays

by Feb 18, 2009

Arrays are by default read/write so you cannot lock down arrays and make them read-only. To create a read-only array, you can "upgrade" it to an ArrayList, though. ArrayLists can then be converted into readonly arraylists:

$array = 1..10
$array += 11
$arraylist = [System.Collections.ArrayList] $array
$readonly = [System.Collections.ArrayList]::ReadOnly($arraylist)
$readonly.GetType().FullName
$readonly
$readonly.isReadOnly
# causes an error because arraylist is readonly:
$readonly.Add("Hello")

However, write-protection is weak. Once you add another element to the array using the += operator, the write-protection breaks:

$readonly += 12
$readonly.isReadOnly

The reason is: PowerShell has silently killed the write-protected ArrayList and replaced it with a new simple array in order to add the new element:

$readonly.GetType().FullName