Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the real use of a Tuple?

Tags:

c#-4.0

Can someone please explain what's the real use of a Tuple ?

like image 317
Embedd_0913 Avatar asked Jan 23 '23 00:01

Embedd_0913


1 Answers

You can think of tuples as being a bit like anonymous types, but without the names - and with the ability to specify return types etc. They're useful when you want an ad hoc multi-value data type, but want to be able to specify that as the return type of a method.

For example, int.TryParse could have had a signature of

static Tuple<int, bool> TryParse(string text)

Basically you want to return an int and a bool. The existing signature uses an out parameter to get around the fact that you can only return a single value - tuples are another option. Likewise KeyValuePair<TKey, TValue> is basically just a pair of values.

Personally I'd like to see another option: a terse way of achieving the semantics of anonymous types (immutability, named properties, equality etc), but with a name.

like image 127
Jon Skeet Avatar answered Jan 24 '23 13:01

Jon Skeet