개념
C# 7 이전 버전에서는 메서드에서 하나의 값만을 리턴할 수 있었지만, C# 7부터는 튜플(Tuple)을 사용하여 메서드로부터 복수 개의 값들을 리턴할 수 있게 되었다.
메서드 원형을 정의할 때 리턴타입이 복수 개이므로 튜플 리턴 타입(tuple return type) 표현식을 사용하게 되는데, 이는 괄호 ( ) 안에 여러 리턴타입을 순서대로 나열하면 된다. 예를 들어, int 2개와 double 하나를 리턴할 경우 (int, int, double)과 같이 표현할 수 있으며, 더 나아가 편의를 위해 각 리턴타입마다 이름을 지정할 수도 있다. 예를 들어 (int count, int sum, double average)와 같이 작성이 가능하다.
(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.
(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.
실제 사용
private (eFile srcFile, int srcRank, eFile dstFile, int dstRank) InputDecoder(string input)
{
Func<char, eFile> fileDecoder = file =>
{
return file switch
{
'a' => eFile.a,
'b' => eFile.b,
'c' => eFile.c,
'd' => eFile.d,
'e' => eFile.e,
'f' => eFile.f,
'g' => eFile.g,
'h' => eFile.h,
_ => throw new ArgumentException($"invalid input. {input}"),
};
};
var file = fileDecoder(input[0]);
var newFile = fileDecoder(input[2]);
if (!int.TryParse(input[1].ToString(), out var rank))
{
throw new ArgumentException($"invalid input. {input}");
}
if (!int.TryParse(input[3].ToString(), out var newRank))
{
throw new ArgumentException($"invalid input. {input}");
}
return (file, rank, newFile, newRank);
}
'프로그래밍 언어 > C#' 카테고리의 다른 글
[C#] switch문에 추가된 기능 (버전 7~9) (0) | 2025.02.03 |
---|---|
[C#] default와 new() 제약 조건 사용하기 (0) | 2024.12.16 |
[C#] Attribute : Obsolete - 더 이상 사용하지 않거나 그럴 예정인 코드에 대해서 (0) | 2024.12.16 |
[C#] IsNullOrEmpty와 IsNullOrWhiteSpace의 차이점 (0) | 2024.11.10 |
[C#] 포인터 관련 unsafe fixed 키워드 (0) | 2024.05.23 |