Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better naming in Tuple classes than "Item1", "Item2"

Tags:

c#

tuples

c#-4.0

Is there a way to use a Tuple class, but supply the names of the items in it?

For example:

public Tuple<int, int, int int> GetOrderRelatedIds()

That returns the ids for OrderGroupId, OrderTypeId, OrderSubTypeId and OrderRequirementId.

It would be nice to let the users of my method know which is which. (When you call the method, the results are result.Item1, result.Item2, result.Item3, result.Item4. It is not clear which one is which.)

(I know I could just create a class to hold all these Ids, but it these Ids already have their own classes they live in and making a class for this one method's return value seems silly.)

like image 723
Vaccano Avatar asked Oct 08 '22 16:10

Vaccano


People also ask

How do you name a tuple?

Creating a Named 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 a tuple in c#?

Starting C# v7. 0, it is now possible to name the tuple properties which earlier used to default to names like Item1 , Item2 and so on.

Why use a tuple instead of a class?

A Tuple will save you time from having to allocate memory on the heap using new for such a simple operation. It doesn't make sense to define a class in this case. No matter what the calculations are the results do not belong to a class.

How do you declare a tuple in C#?

The Tuple<T> class was introduced in . NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types. It can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it.


1 Answers

In C# 7.0 (Visual Studio 2017) there is a new construction to do that:

(string first, string middle, string last) LookupName(long id)
like image 425
MichaelMocko Avatar answered Oct 27 '22 19:10

MichaelMocko