Tuples
A tuple is a small bundle that carries several values together, like a lunch tray holding a sandwich and a drink. It lets a method return more than one thing at once.
In this page:
Syntax
(type, type) tuple = (value1, value2);
static (type Name1, type Name2) MethodName() { return (value1, value2); }
tuple.Item1;
var result = MethodName();
result.Name1;
Tuples
ValueTuple lets a method return multiple values without declaring a dedicated class, written as (int, string) or with named elements.
This is lighter weight than a full class when you just need to group a few related values temporarily. Tuples are value types, so they're compared and copied by value.
Note:
Named tuple elements, like
(int Count, string Label), make the returned values much more readable at the call site.Example: Tuples
using System;
class Program
{
static (int Count, double Average) Analyze(int[] numbers)
{
int sum = 0;
foreach (int n in numbers) sum += n;
return (numbers.Length, (double)sum / numbers.Length);
}
static void Main(string[] args)
{
var result = Analyze(new int[] { 4, 8, 15 });
Console.WriteLine(result.Count);
Console.WriteLine(result.Average);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Reading tuple items as
Item1andItem2when names would be clearer. - Assuming tuples are compared by reference, when they are compared by value.
- Forgetting the parentheses in the tuple syntax.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: