Favicon

Tuple type

Peponi11/20/20244m

C#
SyntaxTypeTupleSystem.ValueTuple

1. Introduction

Tuple은 그룹화된 데이터를 나타내는 값 형식이다. 기본적으로 두 개 이상의 필드를 필요로 한다.

Tuple은 두 가지 형식이 있다. 하나는 여기서 설명할 System.ValueTuple, 그리고 System.Tuple이 있다.

생성할 인스턴스가 자주 쓰는 형식이라면 struct, class, record와 같은 좋은 대안이 있다.

2. Tuple 초기화 및 사용

Tuple은 아래와 같이 초기화한다.

(int, int) intTuple = (1, 2);
 
// 지역 변수인 경우 아래와 같이 초기화 가능
    
void TestMethod()
{
    var intTuple = (1, 2); 
}
 
Console.WriteLine($"{intTuple.Item1}, {intTuple.Item2}");   // 1, 2
// 필드 이름 지정 가능
 
(int Int1, int Int2) intTuple = (1, 2);
 
// 튜플 프로젝션 이니셜라이저
 
var Int1 = 1;
var Int2 = 2;
var intTuple = (Int1, Int2);
 
// 지역변수
    
void TestMethod()
{
    var intTuple = (Int1: 1, Int2: 2); 
}
 
Console.WriteLine($"{intTuple.Int1}, {intTuple.Int2}");     // 1, 2
 
// 필드 이름을 지정해도, 기본 이름으로 접근 가능
 
Console.WriteLine($"{intTuple.Item1}, {intTuple.Item2}");   // 1, 2

Tuple은 메소드 리턴 타입으로도 지정이 가능하다.

(float X, float Y) GetCartesianCoordinate()
{
    var rtnTuple = (10, 20);
    return rtnTuple;
}
 
var coordinate = GetCartesianCoordinate();
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");    // 10, 20
 
// 필드 이름 변경 가능
 
(float XAxis, float YAxis) coordinate = GetCartesianCoordinate();

C# 12 버전부터는 Using 지시문을 이용하여 튜플 형식의 별칭을 지정할 수 있다.

using CartesianCoordinate = (int X, int Y);
 
internal class Program
{
    static void Main(string[] args)
    {
        CartesianCoordinate coordinate = (5, 10);
        Console.WriteLine(coordinate);
    }
}
 
/* output:
(5, 10)
*/

Tuple 특성 상 필드의 위치와 형식만 같다면 다른 별칭으로 변환이 가능하다.

using CartesianCoordinate = (int X, int Y);
using OtherName = (int A, int B);
 
internal class Program
{
    static void Main(string[] args)
    {
        CartesianCoordinate coordinate = (5, 10);
        OtherName other = coordinate;
 
        Console.WriteLine(other);
    }
}
 
/* output:
(5, 10)
*/

3. Tuple 비교

Tuple==, != 연산자를 지원한다. Tuple끼리 비교할 때, 필드의 위치와 형식은 확인하지만 이름은 고려하지 않는다.

var A = (1, 2);
var B = (1, 2);
 
Console.WriteLine(A == B);   // True
Console.WriteLine(A != B);   // False
 
// 캐스팅이 가능한 경우 비교 가능하다.
 
(long, byte) C = (1, 2);
 
Console.WriteLine(A == C);   // True
Console.WriteLine(A != C);   // False
 
// 캐스팅이 불가할 경우 비교 불가능하다.
 
var D = (1, "abc");
 
Console.WriteLine(A == D);   // CS0019: '==' 연산자는 'int' 및 'string' 형식의 피연산자에 적용할 수 없습니다.

4. 참조 자료