I would like to reference a single element inside an array, using the [ref] keyword.
How to test for a reference:
$var1 = "this is a string"
[ref]$var2 = [ref]$var1
$var2.Value
this is a string
$var2.Value += " too!"
$var2.Value
this is a string too!
$var1
this is a string too!
The above is working as expected. But now to reference a single element inside any array?
$var3="string 1", "string 2", "string 3"
[ref]$var2=[ref]($var3[1])
$var2.Value
string 2
$var2.Value += " updated!"
$var2.Value
string 2 updated!
$var3[1]
string 2
I expected $var3[1]
to return the same as the value of $var2.Value
. What am I doing wrong?
So array2[1][3] would be referencing the element of the index of row 1, column 3 (the 2nd row and the fourth column). Another notation that you can use to reference an element of an array is to use a single opening and closing brackets.
To access items in a multidimensional array, separate the indexes using a comma ( , ) within a single set of brackets ( [] ). The output shows that $c is a 1-dimensional array containing the items from $a and $b in row-major order.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].
In PowerShell, you cannot obtain a reference to individual elements of an array.
To gain write access to a specific element of an array, your only option is:
to use a reference to the array as a whole
and to reference the element of interest by index.
In other words:
Given $var3 = "string 1", "string 2", "string 3"
, the only way to modify the 2nd element of the array stored in $var3
is to use $var3[1] = ...
(barring acrobatics via C# code compiled on demand).
As for what you tried:
[ref] $var2 = [ref] ($var3[1])
In PowerShell, if you get the value of $var3[1]
, it is invariably a copy of the data stored in $var3
's 2nd element (which may be a copy of the actual data, if the element contains an instance of a value type, or a copy of the reference to the instance of a reference type, otherwise).
Casting that copy to [ref]
is therefore invariably disassociated from the array element of origin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With