Skip to content

Assigning to an array literal of variables (LHS) should support Deconstruct methods #7471

Open

Description

Steps to reproduce

$tuple = [Tuple]::Create(1, 1)
$item1, $item2 = $tuple

Expected behavior

Tuple.Item1 is assigned to $item1 and Tuple.Item2 is assigned to $item2

Actual behavior

$tuple is assigned to $item1

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      6.1.0-preview.4
PSEdition                      Core
GitCommitId                    6.1.0-preview.4
OS                             Microsoft Windows 10.0.15063
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

While Tuple types aren't used frequently in PowerShell there are a few other default types that have Deconstruct methods like DictionaryEntry and KeyValuePair<,>.

Activity

  1. BrucePay commented on Aug 7, 2018

    @BrucePay
    Collaborator

    For tuples, i definitely agree. (In fact I think we should have more support for tuples (i.e. being able to cast an array to a tuple) being able to "index" on a tuple so $mytuple[0] is equivalent to $mytuble.Item2, etc.).

  2. added
    Issue-Enhancement
    WG-Engine
    on Aug 7, 2018
  3. thezim commented on Aug 8, 2018

    @thezim
    Contributor

    Would love to be able to do stuff like this.

    $domain, $username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -split "\"

    instead of this

    $arr = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -split "\"
    $domain = $arr[0]
    $username = $arr[1]
  4. iSazonov commented on Aug 9, 2018

    @iSazonov
    Collaborator

    Greg Zimmerman (@thezim) Your sample already works. (on Windows with -split "\")

  5. powercode commented on Aug 10, 2018

    @powercode
    Collaborator

    It would be neat to have language syntax for tuples.

  6. vexx32 commented on Aug 13, 2018

    @vexx32
    Collaborator

    The title is misleading as this already works with arrays:
    $one, $two = 1,2 works as expected.

    It doesn't work with tuples, though, and I agree that should be rectified.

  7. SeeminglyScience commented on Aug 13, 2018

    @SeeminglyScience
    ContributorAuthor

    Rain Sallow (/u/ta11ow) (@vexx32) Sorry for the confusion in terminology, when I refer to an array literal assignment I mean an AssignmentStatementAst where the left hand side is an ArrayLiteralAst.

  8. iSazonov commented on Aug 14, 2018

    @iSazonov
    Collaborator

    Please update the issue header.

  9. changed the title [-]Array literal assignments should support Deconstruct[/-] [+]Assigning to an array literal of variables (LHS) should support Deconstruct methods[/+] on Aug 14, 2018
  10. SeeminglyScience commented on Aug 14, 2018

    @SeeminglyScience
    ContributorAuthor

    Thanks Ilya (@iSazonov), title has been updated.

    Also I should fully clarify what I mean by Deconstruct.

    C# 7 added support for assigning each item of a tuple to a different variable in a single assignment.

    Tuple<int, string> tuple = Tuple.Create(1, "test");
    var (first, second) = tuple;

    The way this works is by looking for an instance or extension method named Deconstruct that has out parameters for each item. For tuple, this works because of the extension methods in System.TupleExtensions. The Deconstruct extension method that would be used in the above example has this signature:

    public static void Deconstruct<int, string>(this Tuple<int, string> value, out int item1, out string item2);

    More information

  11. vexx32 commented on Aug 14, 2018

    @vexx32
    Collaborator

    An extension method? Hmm. Well, as long as it's being called from the core parsing logic side of things that should be OK since you're still in a C# realm.

    Extension methods aren't available from PS itself at present, but this should still work, I think

  12. iSazonov commented on Aug 15, 2018

    @iSazonov
    Collaborator

    We have an issue about extension methods.

  13. Jaykul commented on Jun 13, 2020

    @Jaykul
    Contributor

    Yeah, I don't know...

    I think any feature that needs extension method support should be stuck waiting for extension method support -- like the rest of us. I don't like the idea that we might support this one extension method just because we wish to call it automatically 😛

  14. SeeminglyScience commented on Jun 22, 2020

    @SeeminglyScience
    ContributorAuthor

    Joel Bennett (@Jaykul) the feature request itself doesn't actually require extension method resolution, though it would make it a lot more consistent. That said, can you elaborate a bit more on the objection? If a system for resolving extension methods internally within the engine was added for this feature, it would partially add support with less risk. That'd make a full implementation potentially a lot easier down the road.

  15. 12 remaining items

  16. SeeminglyScience commented on Jul 10, 2023

    @SeeminglyScience
    ContributorAuthor

    The Engine WG discussed this issue and concluded that we would love to see the "array assign" syntax support tuples via ITuple.

    Deconstruct support would be nice but is unlikely to be an easy change does not seem to have the impact to justify its complexity. This can be revisited at a later time if sufficient impactful use cases are shown.

  17. added
    Up-for-Grabs
    on Jul 10, 2023
  18. added
    Resolution-No Activity
    on Jan 7, 2024
  19. dkaszews commented on Jan 7, 2024

    @dkaszews
    Contributor

    Bump to keep open

  20. removed
    Resolution-No Activity
    on Jan 7, 2024
  21. added
    KeepOpen
    on Jan 8, 2024
  22. added
    WG-NeedsReview
    on Apr 29, 2024
  23. RiverHeart commented on Dec 26, 2024

    @RiverHeart

    or out parameters I'm not sure powershell supports.

    They're supported by [ref]. Unfortunately, script methods apparently can't be overloaded and the definition only shows as System.Object Deconstruct(); so I guess it's ignored. Defining an overloaded Deconstruct() via class CodeMethod turns the signature into static void Deconstruct(psobject value, ref item1, ref item2) which doesn't get called automatically either.

    function New-Tuple {
        [Alias('tuple')]
        param()
    
        $Deconstruct = {
            param([ref] $item1, [ref] $item2)
    
            $item1.Value = $this.Item1
            $item2.Value = $this.Item2
            return $null
        }
    
        $Tuple = [System.Tuple]::Create.Invoke($args)
    
        Update-TypeData `
            -TypeName $Tuple.GetType().FullName `
            -MemberName 'Deconstruct' `
            -MemberType ScriptMethod `
            -Value $Deconstruct `
            -Force
    
        return $Tuple
    }
    
    $Test1 = 0
    $Test2 = 0
    $Foo = Tuple 'one' 'two'
    
    #$Test1, $Test2 = $foo  # Doesn't work
    $Foo.Deconstruct([ref] $Test1, [ref] $Test2)  # Works

    Personally, think I'll use an Items ScriptProperty since Deconstruct() doesn't seem to be available from PSv5 anyway.

    <#
    .EXAMPLE
        Basic usage
    
        $Foo = *(1, 2, 3)
        $Foo.Items
        $One, $Two, $Three = $Foo.Items
    
    .EXAMPLE
        Pipeline usage
    
        $Foo = (1,2,3) | tuple
        $Foo.Items
        $One, $Two, $Three = $Foo.Items
    #>
    function New-Tuple {
        [CmdletBinding()]
        [Alias('tuple')]
        [Alias('*')]
        param(
            [Parameter(Mandatory,ValueFromPipeline)]
            [Object[]] $InputObject
        )
    
        begin {
            $Accumulator = [System.Collections.Generic.List[Object]]::new()
        }
    
        process {
            if ($MyInvocation.ExpectingInput) {
                $Accumulator.Add($InputObject)
            } else {
                $Accumulator = $InputObject
            }
        }
    
        end {
            $Tuple = [System.Tuple]::Create.Invoke($Accumulator)
            $Items = { $this.psobject.properties | Where-Object { $_.Name -match 'Item\d+' } | Select-Object -ExpandProperty Value }
    
            Update-TypeData `
                -TypeName $Tuple.GetType().FullName `
                -MemberName 'Items' `
                -MemberType ScriptProperty `
                -Value $Items `
                -Force
    
            return $Tuple
        }
    }
  24. mmirreza commented on Apr 9, 2025

    @mmirreza

    Since Powershell 7.4 the function [math]::DivRem() returns a tuple of the quotient and remainder. Now at the latest, we need syntax support to unpack tuples into array by assignment. Actually, it's just an operation override for assignment. Here a try with a casting type:

    #region == C# Class Definition ==
    
    Add-Type -TypeDefinition @"
    using System;
    using System.Linq;
    
    public class NiceTuple
    {
        private object[] _values;
    
        public NiceTuple(params object[] values)
        {
            _values = values;
        }
    
        public static explicit operator NiceTuple(object tuple)
        {
            if (tuple is null)
            {
                throw new ArgumentNullException(nameof(tuple), "The input object cannot be null.");
            }
    
            // Check if the object is a tuple using the 'is' operator
            if (!tuple.GetType().IsGenericType || tuple.GetType().GetGenericTypeDefinition() != typeof(Tuple<>).GetGenericTypeDefinition())
            {
                throw new InvalidCastException("The object is not a System.Tuple.");
            }
    
            // Extract tuple items dynamically
            var properties = tuple.GetType().GetProperties()
                                  .Where(p => p.Name.StartsWith("Item"))
                                  .OrderBy(p => p.Name)
                                  .Select(p => p.GetValue(tuple))
                                  .ToArray();
    
            return new NiceTuple(properties);
        }
    
        public static explicit operator object[](NiceTuple niceTuple)
        {
            return niceTuple._values;
        }
    
        public override string ToString()
        {
            return $"{string.Join(", ", _values)}";
        }
    }
    "@ -Language CSharp
    
    #endregion == C# Class Definition ==
    
    
    #region == Main ==
    
    # Create a System.Tuple with any number of elements
    $tuple = [System.Tuple]::Create(1, "Hello", 3.14, $true)
    
    # Cast the System.Tuple to NiceTuple
    $myNiceTuple = [NiceTuple]$tuple
    
    # Unpack the NiceTuple into variables
    $id, $text, $value, $flag = $myNiceTuple
    
    #endregion == Main ==
  25. added
    WG-Reviewed
    and removed
    WG-NeedsReview
    on Sep 8, 2025
  26. added
    In-PR
    on Dec 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    In-PRIssue-EnhancementKeepOpenUp-for-GrabsWG-EngineWG-Reviewed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions