Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

vb.net

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
like image 386
MichaelS Avatar asked Nov 20 '11 07:11

MichaelS


People also ask

How do you name a tuple?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.

Can you name tuple items C#?

Value tuples can have named fields which greatly improves code readability by allowing precise names to be used instead of the 'Item' properties that are in place for standard tuples. Note that the newer tuples feature uses the System. ValueTuple type (a mutable struct) underneath, rather than System. Tuple (a class).

Can tuple be null?

Null tuples are described in Null Tuples. The data type of each null is never implicit: you must specify which type of null you are using in the expression. A typecheck error. You cannot add an int and a bool.

Are tuples reference types?

Tuple types are reference types. System. ValueTuple types are mutable.


3 Answers

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
like image 188
Jon Skeet Avatar answered Sep 20 '22 04:09

Jon Skeet


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}");
like image 23
Venkatesh Muniyandi Avatar answered Sep 22 '22 04:09

Venkatesh Muniyandi


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 .

like image 31
zmbq Avatar answered Sep 20 '22 04:09

zmbq