You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Assigning to an array literal of variables (LHS) should support Deconstruct methods #7471
In-PRIndicates that a PR is out for the issueIssue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtimeWG-ReviewedA Working Group has reviewed this and made a recommendation
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<,>.
Reacted by Michael Klement, Staffan Gustafsson, Mathias R. Jessen, Oisin Grehan, Anthony Truskinger, Jordan Borean, Rafael Kitover, Santiago Squarzon, ratabb, Dominik Kowalski and 6 more
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.).
Reacted by Patrick Meinecke, Greg Zimmerman, Staffan Gustafsson, Rain Sallow (/u/ta11ow), Oisin Grehan, Dominik Kowalski, Armaan Mcleod and Mehrdad Mirreza
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.
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
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:
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
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 😛
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.
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.
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.
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 ==
In-PRIndicates that a PR is out for the issueIssue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtimeWG-ReviewedA Working Group has reviewed this and made a recommendation
Activity
BrucePay commentedon Aug 7, 2018
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.).
thezim commentedon Aug 8, 2018
Would love to be able to do stuff like this.
instead of this
iSazonov commentedon Aug 9, 2018
Greg Zimmerman (@thezim) Your sample already works. (on Windows with -split "\")
powercode commentedon Aug 10, 2018
It would be neat to have language syntax for tuples.
vexx32 commentedon Aug 13, 2018
The title is misleading as this already works with arrays:
$one, $two = 1,2works as expected.It doesn't work with tuples, though, and I agree that should be rectified.
SeeminglyScience commentedon Aug 13, 2018
Rain Sallow (/u/ta11ow) (@vexx32) Sorry for the confusion in terminology, when I refer to an array literal assignment I mean an
AssignmentStatementAstwhere the left hand side is anArrayLiteralAst.iSazonov commentedon Aug 14, 2018
Please update the issue header.
[-]Array literal assignments should support Deconstruct[/-][+]Assigning to an array literal of variables (LHS) should support Deconstruct methods[/+]SeeminglyScience commentedon Aug 14, 2018
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.
The way this works is by looking for an instance or extension method named
Deconstructthat hasoutparameters for each item. For tuple, this works because of the extension methods inSystem.TupleExtensions. TheDeconstructextension method that would be used in the above example has this signature:More information
vexx32 commentedon Aug 14, 2018
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
iSazonov commentedon Aug 15, 2018
We have an issue about extension methods.
Jaykul commentedon Jun 13, 2020
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 😛
SeeminglyScience commentedon Jun 22, 2020
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.
12 remaining items
SeeminglyScience commentedon Jul 10, 2023
The Engine WG discussed this issue and concluded that we would love to see the "array assign" syntax support tuples via
ITuple.Deconstructsupport 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.dkaszews commentedon Jan 7, 2024
Bump to keep open
RiverHeart commentedon Dec 26, 2024
They're supported by
[ref]. Unfortunately, script methods apparently can't be overloaded and the definition only shows asSystem.Object Deconstruct();so I guess it's ignored. Defining an overloadedDeconstruct()via class CodeMethod turns the signature intostatic void Deconstruct(psobject value, ref item1, ref item2)which doesn't get called automatically either.Personally, think I'll use an
ItemsScriptProperty sinceDeconstruct()doesn't seem to be available from PSv5 anyway.mmirreza commentedon Apr 9, 2025
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:
Add support for assigning ITuple and Deconstruct types to multiple va…