With the introduction of ValueTuple in C# 7, the C# team also introduced support for deconstruction that allows you to split out a ValueTuple in its discrete arguments:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int code; | |
string message; | |
var pair = (42, "hello"); | |
(code, message) = pair; // deconstruct a tuple into existing variables |
The nice thing is that this feature is not limited to tuples; any type can be deconstructed, as long as it has a Deconstruct
method with the appropriate out
parameters:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Version | |
{ | |
public Version(int major, int minor, int build, int revision) | |
{ | |
Major=major; | |
Minor=minor; | |
Build=build; | |
Revision=revision; | |
} | |
public int Major{get;} | |
public int Minor{get;} | |
public int Build{get;} | |
public int Revision{get;} | |
public void Deconstruct(out int major, out int minor, out int build, out int revision) | |
{ | |
major = this.Major; | |
minor = this.Minor; | |
build = this.Build; | |
revision = this.Revision; | |
} | |
} | |
var version =new Version(1,2,3,4); | |
var (major, minor, build, _) = version; |