// 클래스 튜플 타입
Tuple<int, float> tuple1 = new Tuple<int, float>(1, 1.5f);
// 8개까지 사용 가능
Tuple<int, float, int, int, int, int, int, int> tuple2 =
new Tuple<int, float, int, int, int, int, int, int>(10, 2.5f, 10, 10, 10, 10, 10, 10);
// 구조체 튜플 타입
// 마찬가지로 8개까지 사용 가능
ValueTuple<int, float> tuple1 = (3, 2.5f);
(int, float, string) tuple2 = (2, 1.5f, "def"); // 같은 구조체 튜플
// 타입을 명시하지 않고 사용
var t3 = (3, 2.5f, "ghi");
// C#
var t = (num1: 3, num2: 2.5f, word: "ghi");
// 접근 방식
Console.WriteLine($"t : {t}");
Console.WriteLine($"t : {t.Item1}, {t.Item2}, {t.Item3}"); // 요소로 접근
Console.WriteLine($"t1 : {t.ToString()}"); // ToString()메서드로 접근
Console.WriteLine($"t2 : {t.num1}, {t.num2}, {t.word}"); // 이름으로 접근
Output:
t : (3, 2.5, ghi)
t : 3, 2.5, ghi
t1 : (3, 2.5, ghi)
t2 : 3, 2.5, ghi
// C#
// 튜플 할당
(int, double) t1 = (10, 3.14);
(double First, double Second) t2 = (0.0, 1.0);
t2 = t1;
Console.WriteLine($"{nameof(t2)}: {t2.First} and {t2.Second}");
// Output:
// t2: 10 and 3.14
// 튜플 분해
var t = ("post office", 3.6);
(string destination, double distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
// Output:
// Distance to post office is 3.6 kilometers.
// 컴파일러가 해당 형식을 유추하여 분해
var t = ("post office", 3.6);
var (destination, distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
// Output:
// Distance to post office is 3.6 kilometers.
// 기존 변수를 사용하여 분해
var destination = string.Empty;
var distance = 0.0;
var t = ("post office", 3.6);
(destination, distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
// Output:
// Distance to post office is 3.6 kilometers.
// C#
// == 및 =!= 연산에는 변수형식이 고려되지 않음
(int a, byte b) left = (5, 10);
(long a, int b) right = (5, 10);
Console.WriteLine(left == right); // output: True
Console.WriteLine(left != right); // output: False
var t1 = (A: 5, B: 10);
var t2 = (B: 5, A: 10);
Console.WriteLine(t1 == t2); // output: True
Console.WriteLine(t1 != t2); // output: False