Tuple literals with C#

gpeipman
14.2K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Tuple literals with C#

C# 7 introduces tuple literals that make it easier to work with tuples. The problem of tuples have been members with awkward names like Item1, Item2 etc. Tuple literals solve this problem by allowing tuple members have informative names.

Let's start with example where store locator is used to find nearest store for user. There is DummyStoreLocator class that is service layer class and this is something we cannot change (suppose we don't have control over it and we have to use what we have). GetNearestStore() method on Hello class is application layer method and this is what we want to improve.

Click Run to see the demo

Moving to tuples

The code above uses "out" variable to give back store from GetNearestStore() method is application layer. We can argue that returning two independent values from method means new model class or "out" variable but there's also third way - tuples.

Click Run to see the demo

Moving to tuple literals

We were able to eliminate "out" variable from GetNearestStore() but we introduced not informative member names like Item1 and Item2. If we don't have method body opened in code editor we cannot say almost anything about these Item1 and Item2 members. Let's use now tuple literals to make things nice again.

Click Run to see the demo

With tuple literals our code is cleaner and it is easier to understand for other developers working with us.

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content