Tuples
Tuples solve the problem of returning more than one value from a method. Traditionally, we can use out variables that are reference variables, and the value is changed if they are modified from the calling method. However, without parameters, there are some limitations, such as that it cannot be used with async methods and is not recommended to be used with external services.
Tuples have the following characteristics:
- They are value types.
- They can be converted to other Tuples.
- Tuple elements are public and mutable.
A Tuple is represented as System.Tuple<T>, where T could be any type. The following example shows how a Tuple can be used with the method and how the values can be invoked:
static void Main(string[] args) { var person = GetPerson(); Console.WriteLine($"ID : {person.Item1},
Name : {person.Item2}, DOB : {person.Item3}"); } static (int, string, DateTime) GetPerson() { return (1, "Mark Thompson", new DateTime(1970, 8, 11)); }
As you may have noticed, items are dynamically named and the first item is named Item1, the second Item2, and so on. On the other hand, we can also name the items so that the calling party should know about the value, and this can be done by adding the parameter name for each parameter in the Tuple, which is shown as follows:
static void Main(string[] args) { var person = GetPerson(); Console.WriteLine($"ID : {person.id}, Name : {person.name},
DOB : {person.dob}"); } static (int id, string name, DateTime dob) GetPerson() { return (1, "Mark Thompson", new DateTime(1970, 8, 11)); }
https://docs.microsoft.com/en-us/dotnet/csharp/tuples.