New C# 7 features in action: Tuples in C# 7 – tuple types and tuple literals. Sample code for demonstrating the use of Dictionary with values of type Tuple

Tuples enhancements in C# 7

A. tuple types

Some example of the usage of tuple types:

Property of Tuple type

Function with Tuple return type (bool isValid, int errorCode, string errorMessage)

Dictionary with keys of type string and values of type Tuple

B. tuple literals

In below example, tuple literal (false, 3, "Input string only whitespaces")  is used to assign default value to property.

In below example, tuple literal (isValid: success, errorCode: code, errorMessage: message)  is returned by the function.

C. Accessing the tuple elements in a literal

In below example, HasValue function which returns (bool isValid, int errorCode, string errorMessage)  Tuple type is called and output (tuple value) is assigned to result. Then, tuple elements are accessed to form log message.

Another examples:

Full working sample code to demonstrate the C# 7’s Tuples enhancements – tuple types and tuple literals

Note the use of

tuple types –  (bool isValid, int errorCode, string errorMessage)
tuple literals –  (isValid: success, errorCode: code, errorMessage: message)
way of accessing the tuple elements in a literal (result) –  string logMessage = $"{nameof(result.errorCode)}: {result.errorCode}, {nameof(result.errorMessage)}: {result.errorMessage}";

in the below code.

Also, below code demonstrates the use of Dictionary with values of type Tuple.

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 *