The problem

We have the following code that returns a tuple.

public class UserService
{
    public (string, string) GetUser()
    {
        var firstName = "Josef";
        var country = "Sweden";
        return (firstName, country);
    }
}

We can then consume the data like this:

[Fact]
public void ShouldReturnFirstNameAndCountry()
{
    var result = _sut.GetUser();

    result.Item1.ShouldBe("Josef");
    result.Item2.ShouldBe("Sweden");
}

The problem with this approach is that we need to use Item1 and Item2 to access the property values. We need to know that Item1 contains the first name and that Item2 contains the country. That's not a friendly API :). We can do better!

The solution

We can use something called named tuples. This feature was introduced in C# 7.

If you are using a version below C# 7, you will get the following error:

Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.

Named tuples allows us to name the fields in the tuple. We can now write our UserService like this:

public class UserService
{
    public (string FirstName, string Country) GetUser()
    {
        var firstName = "Josef";
        var country = "Sweden";
        return (firstName, country);
    }
}

When consuming the data, we can now use FirstName and Country instead of Item1 and Item2:

[Fact]
public void ShouldReturnFirstNameAndCountry()
{
    var result = _sut.GetUser();

    result.FirstName.ShouldBe("Josef");
    result.Country.ShouldBe("Sweden");
}

Now, we don't need to remember the ordering of the fields returned in the tuple.

All code can be found over at GitHub