Tuple vs KeyValuePair

static Tuple<int, int> GetDivideQuotientRemainder(int a, int b)

{

return new Tuple<int, int>((a / b), (a % b));

}
static KeyValuePair<int, int> GetDivideQuotientRemainder2(int a, int b)

{

return new KeyValuePair<int, int>((a / b), (a % b));

}
static void GetDivideQuotientRemainder3(int a, int b, out int q, out int r)

{

q = (a / b);
r = (a % b);

}

static void Main(string[] args)
{

var value = GetDivideQuotientRemainder(23, 4);
Console.WriteLine(“q = {0} r = {1}”, value.Item1, value.Item2);

var value2 = GetDivideQuotientRemainder2(23, 4);
Console.WriteLine(“q = {0} r = {1}”, value2.Key, value2.Value);

int q = 0;
int r = 0;
GetDivideQuotientRemainder3(23, 4, out q, out r);
Console.WriteLine(“q = {0} r = {1}”, q, r);

}

Tuple (C# 4.0)

튜플은 여러 개의 멤버를 가지는 데이터 구조임 (멤버는 8개까지 가능).
C++의 std::pair 형식과 비슷함.
C#의 KeyValuePair<Tkey, TValue>는 struct 이고, Tuple은 class 임.

var p = new Tuple<string, int>(“HCI”, 2015);
// Item1, Item2, …, Item7, Rest (the final property)
Console.WriteLine(“p={0} {1}”, p.Item1, p.Item2);

// Create() factory method can construct from a 1-tuple to an 8-tuple
var p1 = new Tuple<int, string, double>(1, “hello”, 3.14);
var p2 = Tuple.Create(2, “hci”, 0.001); // Tuple<int, string, double>

// For higher than 8 items, use nested tuple
var p3 = new Tuple<int, int, int, int, int, int, int, Tuple<int, int>>(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9));
Console.WriteLine(“8th={0} 9th={1}”, p3.Rest.Item1, p3.Rest.Item2);

// Use tuple for method return

Tuple<int, int>GetDivideQuotientRemainder(int a, int b)

{

return new Tuple<int, int>( (a/b), (a%b));

}

var value = GetDivideQuotientRemainder(23, 4)

Console.WriteLine(“q={0} r={1}”, value.Item1, value.Item2);