C# Methods: Returning Multiple Values with Efficiency
Unlike C , which relies on references or pointers for returning multiple values, C# offers a cleaner solution: tuples. Introduced in C# 7, tuples provide a concise way to represent a group of values with different data types. This makes returning multiple values from a method significantly easier.
Leveraging Tuples in C#
Tuples are versatile; their primary use here is efficiently returning multiple values.
Illustrative Example
This example showcases how tuples simplify multiple value returns:
(string firstName, string middleName, string lastName) LookupName(long id) { // Data retrieval logic for first, middle, and last names string first = "John"; // Replace with actual retrieval string middle = "Doe"; // Replace with actual retrieval string last = "Smith"; // Replace with actual retrieval return (first, middle, last); // Tuple literal }
The LookupName
method returns a tuple containing three strings. Accessing these values is straightforward:
var names = LookupName(id); Console.WriteLine($"Found {names.firstName} {names.lastName}.");
Named Tuple Elements for Clarity
For enhanced readability, name the tuple elements directly:
(string firstName, string middleName, string lastName) LookupName(long id)
Alternatively, name them within the return statement:
return (firstName: firstName, middleName: middleName, lastName: lastName);
Deconstruction for Simplified Assignment
Tuples support deconstruction, enabling direct assignment of elements to variables:
(string firstName, string middleName, string lastName) = LookupName(id1);
Further Reading
Explore additional examples and applications of C# tuples via the provided link (link not included as it was not provided in the original input).
The above is the detailed content of How Can C# Methods Return Multiple Values Efficiently?. For more information, please follow other related articles on the PHP Chinese website!