using namespace System.Collections.Generic
$example = 9, 4, 3
[List[int]]::new( [int[]]$example ) - I had to type it as an
[int[]]
$stuff = [list[int]] $example $stuff.GetType()is[List[Int]]$stuffpoints to / was assigned to a value that was coerced into that type.- But you can change the
typethat$stuffpoints to with a different type (see examples below)
Warning
Later you can change the datatype that $stuff points to ( example below )
# Implicitly calling the constructor
# I didn't have to type it in this case
# this is type constraint on 'nums' when non null
[List[int]] $nums = @( $example ) $nums.GetType()is[List[Int]- You can't replace it with an incompatible type
$stuff = 314
$nums = 314$stuff.GetType()is now a[int]. It is not an array.$nums.GetType()is still a[List[int]], even though it was set to a single value
Note
$nums.GetType() is still a List, even though It's a single value
$nums = @()Note
$nums.GetType() a [List[int]] with 0 elements
$nums = 'a'
# Error: MetadataError: Cannot convert value "a" to type "System.Int32". Error:
# "The input string 'a' was not in a correct format."Caution
Cannot convert value "a" to type "System.Int32" The input string 'a' was not in a correct format.
Note
nums.GetType() is still the type [List[int]] with 0 elements
You might be able to inspect the constraint if you drill down into
Get-variable 'stuff' -Verbose | Find-Member$nums = $null
$null -eq $nums
# true
$nums.gettype()
# Error: InvalidOperation: You cannot call a method on a null-valued expression.
$nums = @( 'a' )
# MetadataError: Cannot convert value "a" to type "System.Int32". Error:
# "The input string 'a' was not in a correct format."It shows up as being a true null value, but still has some constraints attached
# both don't give a metadata error
$nums = @()
$nums = 100 Note
$nums.GetType() was null
now it's a [List[Int]]
$null -eq $nums # True
$null -eq $nums -and
( (get-variable 'nums' -ea Ignore).count -eq 0 ) # False$nums = $null
$null -eq (Get-variable 'nums' -ValueOnly -ea ignore)
$null -eq (Get-variable 'stuff' -ValueOnly -ea ignore)
# out: True, False
$null -eq (Get-variable 'nums' -ea ignore).count -gt 0
$null -eq (Get-variable 'stuff' -ea ignore).count -gt 0
# out: False, False
# or
$null -eq $nums
$null -eq $ExecutionContext.SessionState.PSVariable.Get('nums')
# out: True, False
Note
If it both exists and is null, -ValueOnly doesn't work as a test for existing
- Why
$null -eq $xvs$x -eq $null? See linter rule PossibleIncorrectComparisonWithNull - The type
[List[Type]]runs onWin Powershell 5andPwsh 7. See Generics in Dotnet
Where does $ExecutionContext.SessionState.PSVariable take place? Maybe in SessionStateScope.cs