C# cho phép trả về Tuple từ một phương thức, cho phép trả về nhiều giá trị cùng lúc mà không cần out parameters hoặc tạo class/struct riêng.
Ví dụ: Trả về Tuple 5 phần tử
static Tuple Show()
{
return Tuple.Create(3, 5, 7, 9, 11);
}
// Gọi
var tuple = Show();
Console.WriteLine(tuple.Item1); // 3
Console.WriteLine(tuple.Item5); // 11
Mã nguồn hoàn chỉnh
using System;
public class Demo
{
public static void Main()
{
var tuple = Show();
Console.WriteLine(tuple.Item1);
Console.WriteLine(tuple.Item2);
Console.WriteLine(tuple.Item3);
Console.WriteLine(tuple.Item4);
Console.WriteLine(tuple.Item5);
}
static Tuple Show()
{
return Tuple.Create(3, 5, 7, 9, 11);
}
}
Kết quả
3
5
7
9
11
Cách hiện đại: ValueTuple (C# 7+)
// Cú pháp ngắn gọn, hiệu suất tốt hơn
static (int, int, int, int, int) ShowModern()
{
return (3, 5, 7, 9, 11);
}
// Gọi với deconstruction
var (a, b, c, d, e) = ShowModern();
// Hoặc named tuple
static (int First, int Second, int Third, int Fourth, int Fifth) ShowNamed()
{
return (3, 5, 7, 9, 11);
}
var result = ShowNamed();
Console.WriteLine(result.Third); // 7
So sánh
| Đặc điểm | Tuple (Class) | ValueTuple (Struct) |
|---|---|---|
| Cú pháp trả về | Tuple<...> | (T1, T2, ...) |
| Truy cập | .Item1 | .Item1 hoặc tên |
| Deconstruction | Không | Có |
| Hiệu suất | Heap | Stack |
Khuyến nghị: Dùng ValueTuple (tuple literal) cho code mới (.NET Core / .NET 5+).