Skip to content

Unexpected behavior of AutomationNull in object initializers using [pscustomobject] #19552

@mklement0

Description

@mklement0

Prerequisites

Steps to reproduce

Note: Initializing via [hashtable] used to break too, but that was fixed in #19402 / #19415.

In an array-type-constrained variable (as in expressions in general), AutomationNull is treated like $null; e.g.:

# Note: & { } is a simple way to return the AutomationNull singleton.
# OK: no error
[string[]] $arr = & { }

By contrast, using AutomationNull in [pscustomobject]-based object initializers fails:

class Example {
   [string[]]$LogMessage
}

$automationNull = & {}

# !! BREAKS: ""Type 'System.String[]' does not have a default constructor (Parameter 'type')""
[Example] [pscustomobject] @{ 'LogMessage' = $automationNull }

The symptom is reminiscent of #19384 (comment)

Expected behavior

An [Example] instance should be constructed, with $null returned from its .LogMessage property.

Note: If this is resolved in the same way as for hashtable initializers, it is actually [System.Management.Automation.Internal.AutomationNull]::Value that is stored in the property, but on accessing (getting) it, it turns to $null.

Outside of a class this behavior is directly visible:

# -> $true
 [object]::ReferenceEquals((
  [string[]] $arr = & { }), 
  [System.Management.Automation.Internal.AutomationNull]::Value
)

Actual behavior

InvalidArgument: 
Cannot convert value "@{LogMessage=}" to type "Example". 
Error: "Type 'System.String[]' does not have a default constructor (Parameter 'type')"

Error details

No response

Environment data

PowerShell Core 7.4.0-preview.3

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or more

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions