What is the purpose of Deconstruct method in KeyValuePair struct?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



What is the purpose of Deconstruct method in KeyValuePair<> struct?



I was looking at System.Collections.Generic.KeyValuePair<TKey, TValue> struct in System.Runtime, Version=4.2.1.0 and this method took my attention.


System.Collections.Generic.KeyValuePair<TKey, TValue>


System.Runtime, Version=4.2.1.0



Here's the signature:


public void Deconstruct(out TKey key, out TValue value);



Does it contain any logic besides simply forwarding Key and Value properties? Why would anyone ever prefer it over property getters?


Key


Value





It’s for the deconstruct syntax introduced in C# 7, see docs.microsoft.com/en-us/dotnet/csharp/deconstruct. The method is not intended to be called directly, but implicitly by writing var (key, value) = SomeMethodReturningAKeyValuePair().
– ckuri
Aug 12 at 14:54


var (key, value) = SomeMethodReturningAKeyValuePair()




1 Answer
1



Deconstruction is a feature that was introduced mainly for value tuples in C# 7, letting you "unpackage all the items in a tuple in a single operation". The syntax has been generalized to allow it to be used for other types too. By defining the Deconstruct method, you can then use concise deconstruction syntax to assign the internal values to individual variables:


Deconstruct


var kvp = new KeyValuePair<int, string>(10, "John");
var (id, name) = kvp;



You can even apply deconstruction to your own user-defined types by defining such a Deconstruct method with out parameters and a void return type, like in your example. See Deconstructing user-defined types.


Deconstruct


out


void






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS