본문 바로가기

Programming/C#

C# 튜플 tuple csharp

728x90

C# 7.0 버전부터 제공하는 튜플(tuple)은 값을 한 번에 하나 이상
전달하거나 제공받을 때 사용하는 데이터 구조

 

튜플 리터럴: 변수에 괄호를 사용하여 값을 하나 이상 설정하는 것

var r = (12, 34, 56);//기본 형태 Item1, Item2, .. 형태
Console.WriteLine($"{r.Item1}, {r.Item2}, {r.Item3}");//12, 34, 56

var square = (Width:1920, Height:1080);//이름 지정
Console.WriteLine($"{square.Width}, {square.Height}");//1920, 1080

(ushort Width, ushort Height) square = (1444, 720);//이름과 형식 지정
Console.WriteLine($"{square.Width}({square.Width.GetType()}), {square.Height}({square.Height.GetType()})");//1444(System.UInt16), 720(System.UInt16)

튜플 반환

static (int, int) GetPoint()
{
    return (10, 20);
}
Console.WriteLine($"{GetPoint().Item1}, {GetPoint().Item2}");//10, 20

static (int x, int y) GetPoint()
{
    return (10, 20);
}
Console.WriteLine($"{GetPoint().x}, {GetPoint().y}");//10, 20
var (x, y) = GetPoint();//튜플 분해
Console.WriteLine($"{x}, {y}");//10, 20

 

728x90