System.ValueTuple – Extended C# Tuples


The C# version #7, the namespace System.Collections.Generics provided the unique collection type called Tuples. In tuples you are allowed to store multiple values belongs to different datatype or object. In my previous article, you can get overview on C# Tuple collection type that provides the basics of Tuples in C#. In this article you will learn extended features of Tuples collection type by importing System.ValueTuple.

The NuGet repository has an extended package System.ValueTuple which implement the underlying types for tuples in C# and Visual Basic. You can reference System.ValueTuple from NuGet manager.

Once the System.ValueTuple is successfully referenced to your project now you can write functions that return tuple values. Prior to writing the code make sure that you have added reference declaration at the beginning of your code file.

Examples:

In the next section you will see few self explanatory example programs that explains how System.ValueTuple allow method to return multiple return values.

Example 1:

In this example, the method GetStudentInfo() return the strongly typed tuple (string, int) and assigned to the implicit variable info declared using var keyword. The student details accessed via info.Item1 and info.Item2 default tuple members.

Example 2:

In this example, the method GetStudentInfo() return the strongly typed tuple with member names (string, int) and assigned to the implicit variable info which is declared using var keyword. The student details accessed via info.StudentName and info.StudentAge explicit tuple members.

Example 3:

In this example, the method GetStudentInfo() return the strongly typed tuple (string, int) and assigned to the explicit variable info which is declared using (string, int). The student details accessed via info.Item1 and info.Item2 default tuple members.

Example 4:

In this example, the method GetStudentInfo() return the strongly typed tuple (string, int) and assigned to the explicit variable info which is declared using (string StudentName, int StudentAge) with tuple members. The student details accessed via info.StudentName and info.StudentAge explicit tuple members.

Example 5:

In the next example, you can see how tuples can be passed as method parameters.

Share this:

Tags:

We will be happy to hear your thoughts

Leave a reply