ใน C# Tuple (System.Tuple) เป็น Immutable Reference Type ไม่สามารถแปลงเป็น Array ได้โดยตรง ต้องสร้าง Array ใหม่และคัดลอกค่าจาก Property Item1, Item2, ... เข้าไป
Tuple 2 ค่า (Pair)
using System;
public class Program
{
public static void Main()
{
Tuple tuple = Tuple.Create(99, 53);
// แปลงเป็น Array ด้วยการสร้างใหม่
int[] arr = new int[] { tuple.Item1, tuple.Item2 };
foreach (int val in arr)
Console.WriteLine(val);
}
}
ผลลัพธ์
99
53
Generic Method สำหรับ Tuple ใดๆ (Reflection)
public static object[] TupleToArray(object tuple)
{
if (tuple == null) return Array.Empty
ValueTuple (C# 7+) - แปลงง่ายกว่า
// ValueTuple (struct) - สร้างง่าย แปลงง่าย
(var a, var b, var c) = (1, "hello", 3.14);
// แปลงเป็น Array ต้องทำ Manual หรือใช้ Reflection
var tuple = (1, "hello", 3.14);
object[] arr = new object[] { tuple.Item1, tuple.Item2, tuple.Item3 };
// หรือใช้ Extension Method
public static object[] ToArray(this (object, object, object) t)
=> new object[] { t.Item1, t.Item2, t.Item3 };
กรณีใช้งานจริง
- Interop กับ API ที่รับ Array/Params
- Serialization ที่ไม่รองรับ Tuple โดยตรง
- Dynamic Programming: ต้องการ Index-based Access
- Reflection/Serialization Libraries
ข้อจำกัด
- Tuple ขนาดคงที่ (Fixed Arity) - ต้องรู้ขนาดตอน Compile-time
- Type Safety: Array จะเป็น object[] หรือ base type ร่วมที่กว้างที่สุด
- Performance: Boxing/Unboxing สำหรับ Value Types
แนะนำ: ใช้ ValueTuple + Pattern Matching (C# 7+)
// แทนที่จะแปลงเป็น Array ให้ใช้ Deconstruction
(int x, int y) = Tuple.Create(10, 20);
// หรือ
var (x, y) = (10, 20); // ValueTuple
// เข้าถึงโดยชื่อ (Named Tuple Elements)
var point = (X: 10, Y: 20);
Console.WriteLine($"{point.X}, {point.Y}");