Saturday, July 3, 2021

PowerShell: Nullable Types

When a variable or parameter is assigned a value of $null it is a convenient way to indicate that the value has not yet been assigned. For by value types such as int, float, char, Guid, DateTime, and TimeSpan the $null assignment has come caveats. This post will introduce PowerShell's Nullable types but first will show why Nullable types are needed.

PowerShell does not generate a warning or error when $null is assigned to an int, double or char variable. 

[int] $anyInt = $null
[double] $anyDouble = $null
[char] $anyChar = $null

Write-Host "AnyInt Value = $anyInt, Is `$null = $($anyInt -eq $null)" 
Write-Host "AnyDouble Value = $anyDouble, Is `$null = $($anyDouble -eq $null)" 
Write-Host "AnyChar Value = $anyChar, Is `$null = $($anyChar -eq $null), Integer Value = $([int]$anyChar)" 

The output of the above Write-Host cmdlets show that $null assignment results in a value of zero being assigned to each of the variables rather than a value of $null:


Assigning $null to variables of type Guid, DateTime, and TimeSpan is shown below:

[Guid] $anyGuid = $null
[DateTime] $anyDateTime = $null
[TimeSpan] $anyTimeSpan = $null

PowerShell displays a warning indicating a $null assignment is not valid for the above code:


Each of the by value data types (int, double, char, Guid, DateTime, and TimeSpan) can be assigned as nullable as shown below using the aptly named Nullable keyword:

[Nullable[int]] $anyInt = $null
[Nullable[double]] $anyDouble = $null
[Nullable[char]] $anyChar = $null
[Nullable[Guid]] $anyGuid = $null
[Nullable[DateTime]] $anyDateTime = $null
[Nullable[TimeSpan]] $anyTimeSpan = $null

Write-Host "AnyInt Value = $anyInt, Is `$null = $($anyInt -eq $null)" 
Write-Host "AnyDouble Value = $anyDouble, Is `$null = $($anyDouble -eq $null)" 
Write-Host "AnyChar Value = $anyChar, Is `$null = $($anyChar -eq $null)" 
Write-Host "AnyGuid Value = $anyGuid, Is `$null = $($anyGuid -eq $null)" 
Write-Host "AnyDateTime Value = $anyDatetime, Is `$null = $($anyDatetime -eq $null)" 
Write-Host "AnyTimeSpan Value = $anyTimeSpan, Is `$null = $($anyTimeSpan -eq $null)" 

When the above Write-Host cmdlets are invoked the value of $null is recognized as being assigned to the variables:







No comments :

Post a Comment