MichaelS
MichaelS

Reputation: 7103

Is there a way to give meaningful names for Tuple items?

Retrieving items from a Tuple is done by accessing the ItemX property. Is there a way of naming each item so that using the Tuple will be more readable?

Code:

Looking for something like this:

Dim l As New Tuple(Of String, Integer)
l.Name
l.ID

Instead of:

Dim l As New Tuple(Of String, Integer)
l.Item1
l.Item2

Upvotes: 7

Views: 4865

Answers (3)

Venkatesh Muniyandi
Venkatesh Muniyandi

Reputation: 5630

In C# 7 Version we have the feature to give friendly name to Tuple Values. Note: Just directly typed the code here not compiled.

e.g

(int Latitude, int Longitude, string city) GetPlace()
{
    return(20,30,"New York");    
}

var geoLocation = GetPlace();
WriteLine($"Latitude :{geoLocation.Latitude}, Longitude:{geoLocation.Longitude}, City:{geoLocation.city}");

Upvotes: 6

zmbq
zmbq

Reputation: 39013

You can write a couple of extension methods for Tuple: First that returns the first element, and Rest that returns a subtuple from the second element onward. That might be both a generic and easy-on-the-eyes solution.

If you call First car and Rest cdr, you're going to make a lot of people very happy http://en.wikipedia.org/wiki/CAR_and_CDR .

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499880

No, there's nothing in the tuple type that helps you out here. Options:

  • If you need to pass the values in multiple methods, create your own type with appropriate properties. (You could derive from Tuple here if you really want, and just provide properties which delegate to Item1 and Item2, but I'm not sure I would)
  • If you only need the values within one method, use an anonymous type

Upvotes: 7

Related Questions