Value Tuples provide a convenient way to return multiple values from a method without defining custom classes or out parameters.
using System;
class Program
{
static void Main()
{
var (sum, product) = CalculateSumAndProduct(5, 10);
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Product: {product}");
}
static (int Sum, int Product) CalculateSumAndProduct(int a, int b)
{
int sum = a + b;
int product = a * b;
// Return a Value Tuple with named elements
return (sum, product);
}
}
In this example:
We define a
CalculateSumAndProduct
method that takes two integers as input and calculates their sum and product.Instead of returning multiple values separately, we return a Value Tuple
(int Sum, int Product)
. Each tuple element has a name (Sum
andProduct
) for improved readability and self-documentation.In the
Main
method, we callCalculateSumAndProduct
, and by using tuple deconstruction(var (sum, product) = ...)
, we can easily extract the individual values.This approach provides a clean and expressive way to return multiple values from a method without introducing custom classes or complex data structures.
Value Tuples are value types, making them efficient and suitable for lightweight data structures.
By effectively using Value Tuples, you can improve the readability and maintainability of your code when you need to return multiple values, and it eliminates the need to create custom classes or use out parameters, resulting in more concise and expressive code.
Top comments (0)