2

C# - Tips and Tricks 02 - Named tuples

 2 years ago
source link: https://josef.codes/c-sharp-tips-and-tricks-02-named-tuples/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C# - Tips and Tricks 02 - Named tuples

8 days agoAugust 29th, 2022

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK