New C# 7 features in action: Deconstruction in C# 7 – deconstructing declaration, deconstructing assignment, deconstructor method and discards in deconstruction.

Deconstruction in C# 7

Deconstruction feature can be used to consume tuples. Also, deconstruction feature can be used for user-defined types in .NET but for that you need to provide Deconstruct method.

public void Deconstruct(out T1 x1, ..., out Tn xn) { ... }

You can provide multiple overloads of Deconstruct method.

Deconstruction for Tuples

Note: HasValue function used in the below examples returns(bool isValid, int errorCode, string errorMessage)  Tuple type.

A. deconstructing declaration

By deconstructing a tuple, you can assign its elements individually to fresh variables as shown below:

B. deconstructing assignment

By deconstructing a tuple, you can also assign its elements individually to existing variables as shown below:

C. discards in deconstruction

C# 7 allows discards in deconstruction, you can ignore the elements of tuple that you don’t require.

Here, we don’t require “errorCode” and “errorMessage”, so we can discard them as shown below:

Deconstruction for User-Defined Types

Note: HasValue function used in the below examples returns OperationResult.

A. deconstructor method

For User-Defined Types, you need to provide Deconstruct method to use deconstruction feature.

B. deconstructor method overload

You can also provide multiple overloaded  Deconstruct methods.

C. deconstructing declaration

The below sample calls Deconstruct(out isValid, out errorCode, out errorMessage);

The below sample calls Deconstruct(out isValid, out logErrorMessage);

D. deconstructing assignment

E. discards in deconstruction

C# 7 allows discards in deconstruction, you can ignore items returned by a Deconstruct method that you don’t require.

Full working sample code to demonstrate the C# 7’s Deconstruction feature-deconstructing declaration, deconstructing assignment, deconstructor method and discards in deconstruction.

Full working sample code to explain the use of Deconstruction for Tuples

CSharp7Sample class contains example to explain: deconstructing declaration, deconstructing assignment and discards in deconstruction.

Full working sample code to explain the use of Deconstruction for User-Defined Types

OperationResult class with overloaded Deconstruct methods.

CSharp7Sample class contains example to explain: deconstructing declaration, deconstructing assignment and discards in deconstruction.

Note: Tuples enhancements needs the ValueTuple types. Add “System.ValueTuple” NuGet package on frameworks that do not include these types.

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone’s Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *