ใช้ ValueTuple (C# 7.0+, .NET Framework 4.7+) ผ่าน Package System.ValueTuple
Syntax
public (int, string, string) GetPerson() { ... }
ตัวอย่าง 1: เรียกผ่าน Item1, Item2...
static (int, string, string) GetFruits()
{
return (Id: 1, FruitName: "Apple", Size: "Big");
}
var fruits = GetFruits();
Console.WriteLine($"Id: {fruits.Item1}, Name: {fruits.Item2}, Size: {fruits.Item3}");
// Fruit Id: 1, Name: Apple, Size: Big
ตัวอย่าง 2: Deconstruction (แนะนำ)
(int FruitId, string FruitName, string FruitSize) = GetFruits();
Console.WriteLine($"Id: {FruitId}, Name: {FruitName}, Size: {FruitSize}");
// Fruit Id: 1, Name: Apple, Size: Big
ข้อดีของ ValueTuple
- Performance ดี (Struct ไม่ใช่ Class)
- ตั้งชื่อ Element ได้ (Named Elements)
- Deconstruction ง่าย
- Immutable โดยค่า Default