Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical example where Tuple can be used in .Net 4.0?

I have seen the Tuple introduced in .Net 4 but I am not able to imagine where it can be used. We can always make a Custom class or Struct.

like image 998
Amitabh Avatar asked Apr 30 '10 14:04

Amitabh


People also ask

When would you use a tuple C#?

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class. We can create a Tuple using the Create method.

Are tuples good practice C#?

Tuple is a great option when you want to combine multiple values (can be different types) into one object without creating a custom class. In this case, Tuple would be a fast and a perfect option to go with.

What is a tuple .NET framework?

A tuple is a data structure that has a specific number and sequence of elements.

Can a tuple have three elements C#?

In C#, a 3-tuple is a tuple that contains three elements and it is also known as triple. You can create a 3-tuple using two different ways: Using Tuple<T1,T2,T3>(T1, T2, T3) Constructor. Using the Create method.


2 Answers

That's the point - it is more convenient not to make a custom class or struct all the time. It is an improvement like Action or Func... you can make this types yourself, but it's convenient that they exist in the framework.

like image 95
tanascius Avatar answered Sep 18 '22 18:09

tanascius


With tuples you could easily implement a two-dimensional dictionary (or n-dimensional for that matter). For example, you could use such a dictionary to implement a currency exchange mapping:

var forex = new Dictionary<Tuple<string, string>, decimal>(); forex.Add(Tuple.Create("USD", "EUR"), 0.74850m); // 1 USD = 0.74850 EUR forex.Add(Tuple.Create("USD", "GBP"), 0.64128m); forex.Add(Tuple.Create("EUR", "USD"), 1.33635m); forex.Add(Tuple.Create("EUR", "GBP"), 0.85677m); forex.Add(Tuple.Create("GBP", "USD"), 1.55938m); forex.Add(Tuple.Create("GBP", "EUR"), 1.16717m); forex.Add(Tuple.Create("USD", "USD"), 1.00000m); forex.Add(Tuple.Create("EUR", "EUR"), 1.00000m); forex.Add(Tuple.Create("GBP", "GBP"), 1.00000m);  decimal result; result = 35.0m * forex[Tuple.Create("USD", "EUR")]; // USD 35.00 = EUR 26.20 result = 35.0m * forex[Tuple.Create("EUR", "GBP")]; // EUR 35.00 = GBP 29.99 result = 35.0m * forex[Tuple.Create("GBP", "USD")]; // GBP 35.00 = USD 54.58 
like image 45
MarioVW Avatar answered Sep 16 '22 18:09

MarioVW