Simplifying Multiple Return Values in C# with Tuples
C# 7 introduced tuples, providing a clean way to return multiple values from a method. This eliminates the need for cumbersome solutions like out parameters or custom classes.
Understanding Tuples
Tuples are immutable data structures capable of holding multiple values of varying types. This makes them ideal for returning diverse data from a single function.
Creating a Tuple-Returning Method
Here's a method LookupName
that uses a tuple to return three strings:
<code class="language-csharp">// Tuple return type (string, string, string) LookupName(long id) { // Fetch first, middle, and last names (from database, etc.) string first = "John"; string middle = "Doe"; string last = "Smith"; return (first, middle, last); // Tuple literal }</code>
Accessing Tuple Values
Access the returned tuple's elements like this:
<code class="language-csharp">var names = LookupName(id); Console.WriteLine($"Found {names.Item1} {names.Item3}."); // Access by index</code>
Named Tuple Elements
For better readability, name your tuple elements:
<code class="language-csharp">// Named tuple elements (string first, string middle, string last) LookupName(long id) { // ... (same retrieval logic as above) ... return (first: first, middle: middle, last: last); // Named tuple literal }</code>
Tuple Deconstruction
C#'s tuple deconstruction simplifies access further:
<code class="language-csharp">(string first, string middle, string last) = LookupName(id); // Deconstruction Console.WriteLine($"Found {first} {last}.");</code>
Further Learning
For more detailed information and examples, consult the official Microsoft documentation:
The above is the detailed content of How Can C# Tuples Simplify Returning Multiple Values from a Method?. For more information, please follow other related articles on the PHP Chinese website!