Skip to content

Assigning the result of an addition (+ operator) with an IList LHS back to that LHS should preserve the list (collection) type #5805

@mklement0

Description

@mklement0

The following idioms should work generically with extensible collections that implement the IList interface and therefore have an .Add(Object) method.

# The following should both call $list.Add($newElement) behind the scenes:
$list = $list + $newElement
$list += $newElement

This would match the current array behavior (although a new array is created every time, given that arrays are fixed-size collections), as well as the behavior with hashtables (with hashtables as the RHS values too).

The current behavior is unexpected:

  • with an unconstrained variable: quietly converts the LHS to an array:
$list = [System.Collections.ArrayList] (1, 2)
$list += 3  # !! Quietly converts the ArrayList to Object[]
$list.GetType().Name . # !! Object[] 
  • with a type-constrained variable: creates a new instance
[System.Collections.ArrayList] $list = 1, 2 # type-constrained ArrayList
$orgList = $list # save reference to original list
$list += 3  # !! Quietly creates a *new instance*
[object]::ReferenceEquals($list, $orgList) # !! $False

Environment data

PowerShell Core v6.0.0-rc.2 (v6.0.0-rc.2) on macOS 10.13.2

Metadata

Metadata

Assignees

Labels

Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtime

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions