Tuples as Method Return Values
Return multiple results without out parameters.
Returning Multiple Values
A method can return only one thing, but a tuple lets that one thing bundle several values, a clean alternative to out parameters.
using System;
class Program
{
static (int, int) Divide(int a, int b) => (a / b, a % b);
static void Main()
{
var result = Divide(17, 5);
Console.WriteLine(result.Item1 + " r " + result.Item2);
}
}Named Tuple Return Types
Naming the returned elements makes the method self-documenting and the call site readable.
using System;
class Program
{
static (int Quotient, int Remainder) Divide(int a, int b)
{
return (a / b, a % b);
}
static void Main()
{
var r = Divide(17, 5);
Console.WriteLine("Q=" + r.Quotient + ", R=" + r.Remainder);
}
}All lessons in this course
- Value Tuples Basics
- Named Tuple Elements
- Deconstruction
- Tuples as Method Return Values