C# 7.0 – Tuples 1


Facebooktwittergoogle_pluslinkedinmail

Tuples first appeared in C# with .NET Framework 4.0. They were supposed to be a lightweight alternative for small classes that were created if a method had to return more than one value.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2017 (15.7.5) and .NET Framework 4.6.1.

            var person = Tuple.Create("John", 24);
            Console.WriteLine(person.Item1);
            Console.WriteLine(person.Item2);

Each element of a tuple could be accessed by appropriate ItemX member – like in the example above. The problem with tuples in such shape is that the code becomes less readable – meaningless Item1, Item2 members. Therefore, the tuple was not widely adopted at that time.

Along with the C# 7.0 release, there was a new concept of tuple introduced. This time they are not just some class from the framework, but they are well integrated with C# language syntax.

Note: To use new tuples you need to install System.ValueTuple NuGet package.

0-install-system-value-tuple-nuget

            var person = ("John", 24);
            Console.WriteLine(person.Item1);
            Console.WriteLine(person.Item2);

You can still use standard ItemX members to access tuple’s values, but there is also a new way.

            var person = (name: "John", age: 24);
            Console.WriteLine(person.name);
            Console.WriteLine(person.age);

Using named members makes the code readable again.

The new tuple is a value type

An old tuple type is reference type – a class. A new tuple syntax generates a value type. This way if a method needs to return a tuple there is no additional object created on the heap.

        (string, int) GetPerson()
        {
            return ("John", 24);
        }

You can also declare a method that returns a tuple with named members.

        (string name, int age) GetPerson()
        {
            return ("John", 24);
        }

Let’s have a look at the last example:

        (string name, int age) FindOfficer(string division, int rank)
        {
            // some code
        }

Did you notice that the left and the right side of ‘FindOfficer’ is very similar? That was made on purpose, so the list of input parameters has the same syntax as the list of output variables.

 

Facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “C# 7.0 – Tuples