Skip to content

Make hashtable literals use type System.Management.Automation.OrderedHashtable #19073

Description

@mklement0

Summary of the new feature / enhancement

Since 7.3, a new, [hashtable]-derived System.Management.Automation.OrderedHashtable type is now available, which provides a backward-compatible implementation that preserves entry-definition order.

As of this writing (as far as I'm aware of), this type is only used with ConvertFrom-Json -AsHashtable.
It would equally be useful in ConvertFrom-StringData and Import-PowerShellDataFile (and potentially other [hashtable]-outputting cmdlets) - see #19070.

Given that the backward-compatibility impact is so low - as was deemed to be the case in the context of ConvertFrom-Json -AsHashtable, see #18524 (comment) - also making hashtable literals use System.Management.Automation.OrderedHashtable seems like a beneficial change, given that:

  • maintaining entry-definition order is always beneficial, at the very least to the human observer
  • the performance impact of maintaining this order is negligible.
# WISHFUL THINKING

PS> @{ foo = 1; bar = 2; zulu = 3; midi = 4 }

Name                           Value  # ENTRY-DEFINITION ORDER PRESERVED
----                           -----
foo                            1
bar                            2
zulu                           3
midi                           4


PS> @{ foo = 1; bar = 2; zulu = 3; midi = 4 }.GetType().FullName
System.Management.Automation.OrderedHashtable

That is, hashtable literals will then be implicitly ordered, without needing an [ordered] pseudo cast.

However, unlike with [ordered] the resulting hashtable will not support direct positional indexing, though it will be available via the .Values collection; that is, the following will be equivalent:

PS> ([ordered] @{ foo = 1; bar = 2; zulu = 3; midi = 4 })[2]
3

# WISHFUL THINKING
PS> @{ foo = 1; bar = 2; zulu = 3; midi = 4 }.Values[2]
3

Proposed technical implementation details (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugWG-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