.NET C# Tip- Use tuple to return multiple values
Jul 13, 2023
As we know tuple is a lightweight data structure. Here we’ll discuss one use case for using tuples.
When we want to return more than one value instead of out parameter, we can use a tuple.
Note: If we have to return multiple values, then we should return a single entity (view model) that has all the return values as properties.
Let us jump to an example.
public class TupleExample
{
public (string field1, string field2) FindMethod()
{
string field1 = string.Empty;
string field2 = string.Empty;
//There is some logic to get details and return field1 and field2
field1 = "field1".
field2 = "field2".
return (field1, field2).
}
}
TupleExample tupleExample = new TupleExample().
var returnValue = tupleExample.FindMethod().
Console.WriteLine($"Use Tuple to return multiple values. \n Return value1- {returnValue.field1} \n Return value2- {returnValue.field2}");
Output
Thanks for reading. Happy coding!