Skip to content

Conversation

@tdykstra
Copy link
Contributor

Fixes #22583

@dotnet-bot dotnet-bot added this to the March 2021 milestone Mar 22, 2021
@tdykstra tdykstra marked this pull request as ready for review March 22, 2021 18:25
@tdykstra tdykstra requested a review from BillWagner as a code owner March 22, 2021 18:25
## Deconstructing user-defined types

C# does not offer built-in support for deconstructing non-tuple types. However, as the author of a class, a struct, or an interface, you can allow instances of the type to be deconstructed by implementing one or more `Deconstruct` methods. The method returns void, and each value to be deconstructed is indicated by an [out](language-reference/keywords/out-parameter-modifier.md) parameter in the method signature. For example, the following `Deconstruct` method of a `Person` class returns the first, middle, and last name:
C# does not offer built-in support for deconstructing non-tuple types other than [`record` types](#deconstructing-a-record-type). However, as the author of a class, a struct, or an interface, you can allow instances of the type to be deconstructed by implementing one or more `Deconstruct` methods. The method returns void, and each value to be deconstructed is indicated by an [out](language-reference/keywords/out-parameter-modifier.md) parameter in the method signature. For example, the following `Deconstruct` method of a `Person` class returns the first, middle, and last name:
Copy link
Member

@IEvangelist IEvangelist Mar 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There another built-in support and it's the KeyValuePair<TKey, TValue>:

foreach (var (key, value) in new Dictionary<int, string>
         {
             [1] = "One", [2] = "Two", [3] = "Three"
         })
{
    Console.WriteLine($"{key} = {value}");
}

I knew about the KVP, but did a quick search for other options.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks!

@tdykstra tdykstra requested a review from IEvangelist March 22, 2021 19:03
Copy link
Member

@IEvangelist IEvangelist left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, :shipit: when you're ready.

@tdykstra tdykstra merged commit 4bade28 into dotnet:main Mar 22, 2021
@tdykstra tdykstra deleted the deconstruct branch March 22, 2021 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Please add note on record-class deconstruct here

3 participants