Vijjendra
Vijjendra

Reputation: 25223

What is main advantage of Tuple?

Can anyone tell me what is the main advantage of using tuple? In what scenarios do I need to use these?

Upvotes: 3

Views: 236

Answers (3)

ChaseMedallion
ChaseMedallion

Reputation: 21764

I assume that you're talking about the Tuple<> type and not anonymous tuple classes.

Like an anonymous type, Tuple<> allows you to avoid declaring a new class just to group a few objects. Unlike anonymous types, tuple types have known names and thus can be used as method return and parameter values, etc.

Personally, I try to avoid heavy use of Tuple<> because it can make for difficult to understand code, expecially when used with primitive types (e. g. if you see a Tuple it's not obvious what each field represents).

One place I have found tuples to be very useful is as dictionary keys. Because Tuples implement Equals() and GetHashCode() (not ==, though!), they are perfect for things like private dictionaries that cache information based on a compound key.

Upvotes: 4

user34537
user34537

Reputation:

Lets say I have a list of urls to go through and if i get an error (4xx or 5xx) I want to build a list and then either later display it to the user or just look at it in my debugger.

I'd catch the web exception and have a Tuple<string, int> (url, http error code) instead of creating a struct for one or two functions to use. Heck it might even be a foreach loop with a breakpoint on if the list has more then 0 items. Thats when it is useful.

Upvotes: 0

carlosfigueira
carlosfigueira

Reputation: 87228

It's used mostly to avoid declaring a class / struct with a few properties only for the sake of passing a group of objects around, where only one object can be passed.

Upvotes: 2

Related Questions