Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Unexpected behavior of AutomationNull in object initializers (hashtable or [pscustomobject]) #19402

Copy link
Copy link
@mklement0

Description

@mklement0
Issue body actions

Prerequisites

Steps to reproduce

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, and $null is assigned.
[string[]] $arr = & { }

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

class Example {
   [string[]]$LogMessage
}

$automationNull = & {}

# !! BREAKS: "Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.String[]'"
[Example] @{ 'LogMessage' = $automationNull }

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

That the [pscustomobject]-based initialization breaks differently is surprising, and reminiscent of #19384 (comment)

Expected behavior

Two [Example] instances should be constructed, with $null in the .LogMessage property.

Actual behavior

Both initializations fail, albeit differently:

InvalidArgument: /path/to/script.ps1:13
Line |
  13 |  [Example] @{ 'LogMessage' = $automationNull }
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot create object of type "Example". Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.String[]'.
InvalidArgument: /path/to/script.ps1:16
Line |
  16 |  [Example] [pscustomobject] @{ 'LogMessage' = $automationNull }
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert value "@{LogMessage=}" to type "Example". Error: "Type 'System.String[]' does not have a default constructor (Parameter 'type')"

Error details

See above.

Environment data

PowerShell 7.4.0-preview.2

Visuals

No response

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.