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.
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.
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.
A tuple is a data structure that has a specific number and sequence of elements.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With