티스토리 뷰
함수를 정의 하다보면, 여러개의 변수를 반환하고 싶을 때가 있다. 또는 여러개의 연관된 변수를 묶어 사용하고 싶기도 하다. 그러나 새로운 타입의 객체를 생성하기 부담스러운 경우(객체 너무 많아...한번 쓰고 버릴건데..)
튜플을 사용해볼 수 있다.
1. Tuple 사용하기
public void Example()
{
var colorInfo = GetColor();
Console.WriteLine($"name: {colorInfo.Item1} " +
$"r:{colorInfo.Item2} " +
$"g:{colorInfo.Item3} " +
$"b:{colorInfo.Item4}");
// Output
// name: red r:255 g:0 b:0
}
public Tuple<string, int, int, int> GetColor()
{
return System.Tuple.Create("red", 255, 0, 0);
}
위와 같이 튜플의 장점은 간결한 데이터 구조로 여러 데이터 요로슬 그룹화 하는 간결한 구문을 제공한다. 그러나 위와 같이 사용하면, Item1, Item2로 접근해야 되기 때문에 구조화된 데이터의 의미를 파악하기는 어렵다.
2. Tuple 필드의 이름 지정하기
Tuple 필드의 이름을 지정하는 기능은 C# 7.0 부터 제공한다. 아래와 같이 멤버 변수에 접근할 수 있는 이름을 별도로 지정 할 수 있다.
public void Example()
{
ar colorInfo = GetColor();
Console.WriteLine($"name: {colorInfo.Name} " +
$"r:{colorInfo.R} " +
$"g:{colorInfo.G} " +
$"b:{colorInfo.B}");
// Output
// name: blue r:0 g:255 b:0
}
public (string Name, int R, int G, int B) GetColor()
{
return ("blue", 0, 255, 0);
}
이상 오늘의 검토 꿀팁 :D
Reference
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples
Tuple types - C# reference
Learn about C# tuples: lightweight data structures that you can use to group loosely related data elements
docs.microsoft.com
'Computer Engineering > C#(.Net)' 카테고리의 다른 글
[C#] Await, Async - 비동기 프로그래밍 (0) | 2022.06.28 |
---|---|
[C#] 직렬화를 이용하여 Deep Copy하기 (0) | 2022.06.15 |
[C#] Attribute([])를 알아보자.! (0) | 2022.05.12 |
[C#] string 과 StringBuilder (0) | 2022.04.13 |
[C#] VScode에서 C# 콘솔 어플리케이션 만들기 (0) | 2022.04.05 |