How to name tuple properties?

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

(string first, string middle, string last) LookupName(long id)

This is not possible with Tuple, no. You'll need to create your own new named type to do this.


You need to declare a helper class to do so.

public class MyResult
{
    public string Name { get; set; }
    public string Age { get; set; }
}

What you're trying to return is an anonymous type. As the name suggests you don't know what its name is, so you can't declare your method to return it.

Anonymous Types (C# Programming Guide)

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Update

C#7 introduces Tuple support built into the language and it comes with named tuples

(string name, int age) methodTuple()
{
    (...)
}

Read more on docs.microsoft.com: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#tuples


Starting C# v7.0, it is now possible to give custom name to tuple properties. Earlier they used to have default names like Item1, Item2 and so on.

Naming the properties of Tuple Literals:

var personDetails = (Name: "Foo", Age: 22, FavoriteFood: "Bar");
Console.WriteLine($"Name - {personDetails.Name}, Age - {personDetails.Age}, Favorite Food - {personDetails.FavoriteFood}");

The output on console:

Name - Foo, Age - 22, Favorite Food - Bar

Returning Tuple (having named properties) from a method:

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Foo", "Bar", "Foo-PC", 1000);
}

The output on console:

Employee Details: Foo, Bar, Foo-PC, 1000

Creating a list of Tuples having named properties

var tupleList = new List<(int Index, string Name)>
{
    (1, "cow"),
    (5, "chickens"),
    (1, "airplane")
};

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

Output on console:

1 - cow  
5 - chickens  
1 - airplane

Note: Code snippets in this post are using string interpolation feature of C# which was introduced in version 6 as detailed here.

Tags:

C#

Tuples